2011-09-29 102 views
0

我有一個父模型默認情況下和嵌套模型。嵌套模型本身具有propertyA,它是具有defaultValue和userValue的對象。這個想法是父模型的每個實例都帶有一個嵌套模型,該模型的userValue爲null,並且具有靜態默認值。backbone.js嵌套模型的對象不是唯一的實例

問題是,當我更新一個實例的userValue時,它最終會改變所有前進的實例。我沒有更新特定實例的userValue,而是更新了嵌套模型「prototype」。

下面的代碼可在http://jsfiddle.net/GVkQp/4/。感謝幫助。

var ParentModel = Backbone.Model.extend({ 
    initialize: function(){ 
     var defaultObjs = { 
      nestedModel : new NestedModel() 
     }; 
     $().extend(this.attributes, defaultObjs); 
    } 
}); 


var NestedModel = Backbone.Model.extend({ 
    defaults: { 
     "propertyA" : { 
         "defaultValue" : "ABC", 
         "userValue": null 
         } 
    } 
}); 

var ParentView = Backbone.View.extend({ 
    initialize: function(){ 
     var self = this; 
     var defaultValue = self.model.get("nestedModel").get("propertyA")["defaultValue"]; 
     var userValue = self.model.get("nestedModel").get("propertyA")["userValue"]; 

     var div = $("<div class='box'>defaultValue = <span id='defaultValue'>" + 
        defaultValue+ "</span>, userValue = <span id='userValue'>" + 
        userValue + "</span></div>"); 
     var divButton = $('<input type="button" value="Change my userValue to DEF">') 
      .click(function(){ 
      temp = self.model.get("nestedModel").get("propertyA"); 
      temp.userValue = "DEF"; 
      //wherewas my intention is just to set the userValue for a particular instance, 
      //generating another instance of ParentView (by clicking button) reveals that 
      //the userValue is set even for new instances. 
      //How can I change it such that I only change the userValue of the particular 
      //instance? 

      //set value 
      self.model.get("nestedModel").set({"propertyA": temp}); 

      //update userValue in View 
      userValue = self.model.get("nestedModel").get("propertyA")["userValue"]; 
      $(this).parent().find("span#userValue").text(userValue);  
     });  

     //append divButtont to div 
     div.append(divButton) 

     //append div to body 
     $('body').append(div) 
    }, 
}); 

$("#add").click(function(){ 
    var newBoxView = new ParentView({ 
     model: new ParentModel() 
    }); 
}); 

回答

3

感謝您的jsFiddle。它完美地說明了你的問題。

您會發現,當您將默認值設置爲「propertyA」時,您創建的對象將與您創建的每個其他嵌套類一起被複制。出於這個原因,當你定義你的defaults時,你可以選擇將其定義爲一個函數,以便每次創建新的默認值。如果你這樣做,你可以解決你的問題:

var ParentModel = Backbone.Model.extend({ 
    defaults: function() { 
     return {nestedModel: new NestedModel()}; 
    } 
}); 


var NestedModel = Backbone.Model.extend({ 
    defaults: function() { 
     return { 
     "propertyA" : { 
         "defaultValue" : "ABC", 
         "userValue": null 
         } 
     }; 
    } 
}); 
相關問題