backbone.js嵌套模型的对象不是实例唯一的

时间:2011-09-29 06:13:03

标签: javascript jquery backbone.js

我有一个默认具有嵌套模型的父模型。嵌套模型本身具有propertyA,它是一个具有defaultValue和userValue的对象。我们的想法是,父模型的每个实例都带有一个嵌套的模型,其userValue为null,并且具有静态默认值。

问题是,当我更新一个实例的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()
    });
});

1 个答案:

答案 0 :(得分: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
                      }
        };
    }
});