我使用更改事件在 Backbone 中发现了一些奇怪的东西。它带有一个具有数组作为属性的模型。如果我让属性在里面推送一个新值并将其设置回模型,则不会触发更改事件......
这是一个完整记录的示例:
var TestModel = Backbone.Model.extend({
defaults : {
numbers : []
},
initialize : function() {
this.on('change:numbers', this.changedEvent);
},
changedEvent : function() {
console.log('model has changed');
}
});
var oTestModel = new TestModel();
oTestModel.set('numbers', [2, 3, 4]); // change:numbers Event is fired
var aNumbers = oTestModel.get('numbers');
aNumbers.push(5);
oTestModel.set('numbers', aNumbers); // change:numbers event is NOT fired BUT WHY???
// oTestModel.set('numbers', [2, 3, 4]);
// If this line is not commented out change:numbers event is also fired
console.log(oTestModel.toJSON()); // Dumps out [2,3,4,5] Respective [2,3,4] if line above is not commented out
提前谢谢。