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()
});
});