2015-05-22 68 views
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

我該如何避免昂貴的淺拷貝,並觸發更改事件?

回答

1

該方法不起作用,因爲Backbone無法檢測到您已更改object_attr對象。這不是一般JavaScript問題的Backbone問題 - 您無法觀察對象屬性更改(yet)。

與變更事件設置深屬性的最好方法是使用像Backbone.DeepModel一個插件,它覆蓋set嵌套屬性的工作:

var ModelHasObjectAttribute = Backbone.Model.extend({ 
    // ... 
    setYear:function(year) { 
    // triggers 'change' events 
    this.set('object_attr.year', year); 
    }, 
    // ... 
} 

注:鏈接是最近的DeepModel分支。根據您的應用設置,您可能需要使用(unmaintained) original version

+0

謝謝你的回答!我認爲這是一個好主意,我也使用了一種解決方法,那就是使object_attr成爲一個Backbone模型 –

相關問題