Reputation: 1789
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
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: []
}
},
...
});
Upvotes: 2