Backbone-model数组字段更改会导致类中的更改

时间:2012-05-31 11:29:03

标签: javascript backbone.js

我有一个问题,默认情况下使用数组创建模型。也许我错过了什么?

    $(document).ready(function(){
        Person = Backbone.Model.extend({
            defaults:{
                children:[]
            },        
            add: function(child){
                var children_array = this.get('children');
                children_array.push(child);
                this.set({children:children_array});
            }
        });

//create with default constructor
        var person = new Person();
//add 2 child
        person.add('John');
        person.add('Jane');
        alert(person.get('children'));

//create another one    
        var person1 = new Person();    
//already have 2 children!
        alert(person1.get('children'));    

        var person2 = new Person({children: []});    
//that's work
        alert(person2.get('children'));    
    })

演示:http://jsfiddle.net/GA68X/2/

1 个答案:

答案 0 :(得分:2)

  

请记住,在JavaScript中,对象是通过引用传递的,因此如果您将对象包含为默认值,它将在所有实例之间共享。

http://documentcloud.github.com/backbone/#Model-defaults

试试这个:

 Person = Backbone.Model.extend({
     defaults: function () {
         return {
             children: []
         }
     },        
     ...
});

http://jsfiddle.net/UBdQp/1/