http://backbonejs.org/#Model-defaults
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. Instead, define defaults as a function.
##Problème##
var Human = Backbone.Model.extend({
defaults : {
firstName:"John",
lastName:"Doe",
friends:[]
}
});
var bob = new Human({firstName:"Bob", lastName:"Morane"});
var john = new Human()
var jane = new Human({firstName:"Jane"})
bob.get("friends").push(john, jane)
jane.get("friends"); -> wrong number of friends
john.get("friends"); -> wrong number of friends
##Solution##
var Human = Backbone.Model.extend({
defaults : function() {
return {
firstName:"John",
lastName:"Doe",
friends:[]
}
}
});