我有一个叫做主题的模型。 主体的一个属性称为接收器,由一组对象组成。 我想从对象数组中创建一个集合。
在主题视图中我这样做:
var receivers = this.model.get('receivers');
在控制台中一切都很好看。现在,接收器变量由五个对象组成,如预期的那样。
然后我这样做:
var receiversCollection = new App.Collections.Receivers( receivers );
现在,当我检查receiversCollection时,它只包含两个奇怪的对象:
child {length: 2, models: Array[2], _byId: Object, constructor: function, model: function…}
我做错了什么?
编辑 - 下面包含的附加信息。
这些是我的定义:
App.Models.Receiver = Backbone.Model.extend({
defaults: {
first_name: '',
last_name: '',
email: '',
location: '',
created_at: null,
updated_at: null
}
});
App.Collections.Receivers = Backbone.Collection.extend({
model: App.Models.Receiver
});
这就是控制台中五个接收器的样子:
0: Object
created_at: "0000-00-00 00:00:00"
email: "info@example.com"
first_name: "Adam"
id: "1"
last_name: "Bertilsson"
location: "Stockholm"
pivot: Object
updated_at: "2013-04-16 07:33:26"
__proto__: Object
1: Object
created_at: "0000-00-00 00:00:00"
email: "info@example.com"
first_name: "Sven"
id: "2"
last_name: "Svensson"
location: "Uppsala"
pivot: Object
updated_at: "0000-00-00 00:00:00"
__proto__: Object
2: Object
created_at: "0000-00-00 00:00:00"
email: "info@example.com"
first_name: "Adam"
id: "1"
last_name: "Bertilsson"
location: "Stockholm"
pivot: Object
updated_at: "2013-04-16 07:33:26"
__proto__: Object
3: Object
created_at: "0000-00-00 00:00:00"
email: "info@example.com"
first_name: "Adam"
id: "1"
last_name: "Bertilsson"
location: "Stockholm"
pivot: Object
updated_at: "2013-04-16 07:33:26"
__proto__: Object
4: Object
created_at: "0000-00-00 00:00:00"
email: "info@example.com"
first_name: "Sven"
id: "2"
last_name: "Svensson"
location: "Uppsala"
pivot: Object
updated_at: "0000-00-00 00:00:00"
__proto__: Object
length: 5
__proto__: Array[0]
这就是控制台中的receiversCollection:
_byId: Object
1: child
2: child
c56: child
c57: child
__proto__: Object
length: 2
models: Array[2]
0: child
1: child
length: 2
__proto__: Array[0]
__proto__: Surrogate
答案 0 :(得分:1)
这里的问题是因为重复的ID。
Id's must be unique..
在创建集合时,它会通过id's
进行浏览,因为前两个模型在集合中有unique id still not present
,它们会被添加。
其他人被忽略,因为具有该ID的模型已经存在于集合中。
尝试编辑模型的ID,瞧,你会在集合中看到5个模型。