当特定属性发生变化时,Backbone模型触发自定义事件的好方法是什么?
到目前为止,这是我得到的最好的:
var model = Backbone.Model.extend({
initialize: function(){
// Bind the mode's "change" event to a custom function on itself called "customChanged"
this.on('change', this.customChanged);
},
// Custom function that fires when the "change" event fires
customChanged: function(){
// Fire this custom event if the specific attribute has been changed
if( this.hasChanged("a_specific_attribute") ){
this.trigger("change_the_specific_attribute");
}
}
})
谢谢!
答案 0 :(得分:2)
您已经可以绑定到特定于属性的更改事件:
var model = Backbone.Model.extend({
initialize: function () {
this.on("change:foo", this.onFooChanged);
},
onFooChanged: function () {
// "foo" property has changed.
}
});
答案 1 :(得分:1)
Backbone已经有一个事件“change:attribute”,它会针对每个已更改的属性触发。
var bill = new Backbone.Model({
name: "Bill Smith"
});
bill.on("change:name", function(model, name) {
alert("Changed name to " + name);
});
bill.set({name : "Bill Jones"});