1
我寫一條測試代碼:是在Backbone.js的「變化」事件只是「參考基礎」轉變,而不是「基於價值」的改變
var ModelHasObjectAttribute = Backbone.Model.extend({
defaults:{
property_value:99 ,
object_attr:{"year":"1990"}
},
setYear:function(year) { // function like this cannot trigger change
var temp_object_attr = jQuery.extend({}, this.get('object_attr') ); // This shallow copy is to change the reference of object_attr,
temp_object_attr["year"] = year; // otherwise I cannot trigger 'change' event, if the value of one attribute changed but reference not changed
this.set('object_attr', temp_object_attr);
},
changeYear:function(year) {
console.log("before changing, " + this.get('object_attr')['year']);
this.get('object_attr')["year"] = year;
console.log(this.get('object_attr'));
},
initialize: function() {
var classRef = this;
this.on('change:property_value', function() {
alert("heard property_value changing");
});
this.on('change:maxvalue', function() {
alert("heard maxvalue changing");
});
this.on('change:object_attr', function() {
alert('heard object_attr changing' + classRef.get('object_attr')['year']);
});
}
});
var on_instance = new ModelHasObjectAttribute();
on_instance.set('property_value',10);
on_instance.changeYear(2015); // this line of code does not trigger default 'change' event
on_instance.setYear(2016); // this one triggered
console.log(on_instance.get('object_attr'));
例如,如果我想change
被觸發當object_attr
更改時, 我必須更改存儲在object_attr
下的對象的引用。 只是修改對象的值爲object_attr
,不會觸發change
。
我該如何避免昂貴的淺拷貝,並觸發更改事件?
謝謝你的回答!我認爲這是一個好主意,我也使用了一種解決方法,那就是使object_attr成爲一個Backbone模型 –