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

newest questions tagged jquery – Stack Overflow

About Admin