Eugene
Eugene

Reputation: 1789

Backbone-model array field changes causes changes in class

I have a problem, when create model with array by defaults. Maybe I missed something?

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

Demo: http://jsfiddle.net/GA68X/2/

Upvotes: 0

Views: 62

Answers (1)

theotheo
theotheo

Reputation: 2702

Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances.

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

Try this:

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

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

Upvotes: 2

Related Questions