如何监视Backbone中的变量更改

Ben*_*der 2 javascript backbone.js backbone-views

我有一个视图,其中有一个属性headerClass,我在视图的顶部定义,并在各种方法中通过执行更改值this.headerClass = 'new value'.

但是,如何监视此变量的更改?我尝试添加this.headerClass.on("change", this.render, this);但是在执行此操作时出现错误.

以下是我的代码

MyView = Backbone.View.extend({
    el: $(".header"),
    template: _.template($("#header-template").html()),
    headerClass: 'normal',

    initialize: function () {
        this.render();

        //This doesn't seem to work
        this.headerClass.on("change", this.render, this);
    },

    render: function () {
        this.$el.html(this.template({headerClass: this.headerClass}));
        return this;
    },

    changeClass: function () {
        //When the value changes I want to re-render the view
        this.headerClass: 'fluid';
    }
});
Run Code Online (Sandbox Code Playgroud)

Lix*_*Lix 6

我建议setter为这个属性实现一种函数.每次使用新值调用此函数时,视图都会触发事件.

set_headerClass: function (value) {
    this.headerClass = value;
    this.trigger("changed:headerClass");
}
Run Code Online (Sandbox Code Playgroud)

您现在可以向视图添加侦听器并监视更改:

initialize: function () {
    ...
    // Will re-render the view when the event is detected.
    this.on("changed:headerClass", this.render, this);
},
Run Code Online (Sandbox Code Playgroud)

如果要更改headerClass值,可以通过调用setter函数来实现:

changeClass: function () {
    this.set_headerClass('fluid');
}
Run Code Online (Sandbox Code Playgroud)