覆盖主干'set'方法

时间:2013-07-29 11:09:41

标签: backbone.js

我想覆盖骨干集方法,这样每当我将一个值设置为骨干模型时,就会调用在该属性上注册的回调而不检查该属性的相同先前值。

var model = Backbone.Model.extend({
     defaults : {
         prop1 : true 
     }
});

var view = Backbone.View.extend({
     initialize : function(){
        this.listenTo(this.model,"change:prop1", this.callback);

     },
     callback : function(){
        // set is called on prop1
     }
});

var m1 = new model();
var v1 = new view({model:m1});
m1.set("prop1",true); // It doesn't trigger callback because I'm setting the same value to prop1

2 个答案:

答案 0 :(得分:19)

您可以在骨干模型集中编写一个新方法,如下所示:

var model = Backbone.Model.extend({
     defaults: {
         prop1: true;
     },

     // Overriding set
     set: function(attributes, options) {
        // Will be triggered whenever set is called
        if (attributes.hasOwnProperty(prop1)) {
           this.trigger('change:prop1');
        }  

        return Backbone.Model.prototype.set.call(this, attributes, options);
     }
});   

答案 1 :(得分:0)

实际上,函数set的签名与接受答案中描述的签名不同。

export var MyModel = Backbone.Model.extend({
    set: function (key, val, options) {
        // custom code
        var result = Backbone.Model.prototype.set.call(this, key, val, options);
        // custom code
        return result;
    }
});

请参阅: