我有一个问题,默认情况下使用数组创建模型。也许我错过了什么?
$(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'));
})
答案 0 :(得分:2)
请记住,在JavaScript中,对象是通过引用传递的,因此如果您将对象包含为默认值,它将在所有实例之间共享。
http://documentcloud.github.com/backbone/#Model-defaults
试试这个:
Person = Backbone.Model.extend({
defaults: function () {
return {
children: []
}
},
...
});