backbone.js nested model's object not unique to instance
I have a parent Model that has by default and nested Model. The nested Model itself has propertyA, which is an object with defaultValue and userValue. The idea is that every instance of parent Model comes with a nested Model that has a userValue of null, and a static default value.
The problem is, when I update the userValue for one instance, it ends up changing for all instances going forward. Instead of updating the userValue for a particular instance, I'm doing something wrong and updating the nested Model "prototype".
Below code available at http://jsfiddle.net/GVkQp/4/. Thanks for help.
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 clickin开发者_StackOverflow社区g 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()
});
});
Thanks for the jsFiddle. It illustrates your problem perfectly.
You see, when you set your "propertyA" in your defaults, the object you create is the default value being copied along with every other nested class you create. For this reason, when you define your defaults
, you have the option to define it as a function in order to create the default value new every time. If you do this, you solve your problem:
var ParentModel = Backbone.Model.extend({
defaults: function() {
return {nestedModel: new NestedModel()};
}
});
var NestedModel = Backbone.Model.extend({
defaults: function() {
return {
"propertyA" : {
"defaultValue" : "ABC",
"userValue": null
}
};
}
});
精彩评论