8

我想我想做的很简单,我只是不知道该怎么做。我想在我的模型属性之一发生更改以将某些数据传递给事件处理程序时触发我自己的事件(无论更改是增加还是减少值)。

基本上我希望我的处理程序在视图中执行此操作

handler: function(increased) {
   if(increased) {
      alert("the value increased")
   }
   else {
      alert("the value decreased")
   }
}

// ...

this.model.on("change:attr", this.handler, this);
4

3 回答 3

12

给你:你基本上听change:myvar。当发生更改时,您可以使用模型previous()来获取旧值。根据它是增加还是减少,您会触发相应的事件。您可以收听这些事件,如initialize().

(function($){

    window.MyModel = Backbone.Model.extend({

        initialize: function () {
            this.on('change:myvar', this.onMyVarChange);
            this.on('increased:myvar', function () {                  
                console.log('Increased');                
            });
            this.on('decreased:myvar', function () {                  
                console.log('Decreased');                
            });
        },

        onMyVarChange: function () {
            if (this.get('myvar') > this.previous('myvar')) {
                this.trigger('increased:myvar');  
            } else {
                this.trigger('decreased:myvar');
            }
        }            
    });

    window.mymodel = new MyModel({myvar: 1});
    mymodel.set({myvar: 2});
    mymodel.set({myvar: 3});
    mymodel.set({myvar: 1});

})(jQuery);​

运行上述命令将在控制台打印“Increased”、“Increased”、“Decreased”。

于 2012-02-25T11:58:13.413 回答
2

看看previousAttributes()

然后你可以比较:

If(this.get(attr) > this.previousAttributes()[attr]){
    console.log('bigger');
} else {
    console.log('smaller');
}

如果你在你的change事件处理程序中使用它,你就准备好了。无需自定义触发器或大量代码。

编辑

这来自我的Backbone.Validators项目以及我如何获取在验证步骤期间更改的所有属性的列表:

var get_changed_attributes = function(previous, current){
    var changedAttributes = [];
    _(current).each(function(val, key){
        if(!_(previous).has(key)){
            changedAttributes.push(key);
        } else if (!_.isEqual(val, previous[key])){
            changedAttributes.push(key);
        }
    });
    return changedAttributes;
};

这需要下划线 1.3.1,因为它使用_.has. 如果您无法升级,那很容易更换。在你的情况下,你会通过this.previousAttributes()并且this.attributes

于 2012-02-25T12:03:35.353 回答
0

如果您在听完更改事件后触发自己的自定义事件怎么办?

handler: function(increased) {
   this.model.trigger('my-custom-event', stuff, you, want);
},
myHandler: function(stuff, you, want){
    // Do it...
}
// ...
this.model.on("change:attr", this.handler, this);
this.model.on('my-custom-event, this.myHandler, this);
于 2012-02-25T05:42:44.730 回答