gpt4 book ai didi

backbone.js - 覆盖主干 'set' 方法

转载 作者:行者123 更新时间:2023-12-04 09:40:53 24 4
gpt4 key购买 nike

我想覆盖主干设置方法,以便每当我为主干模型设置一个值时,在该属性上注册的回调都会被调用,而无需检查该属性的先前值是否相同。

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

最佳答案

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

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);
}
});

关于backbone.js - 覆盖主干 'set' 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17922503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com