假设有2个类别,分别代表/api/page/1
和/api/page/2
; 反正是有(通过下划线,例如)合并这2个集合到一个新的,单一的收藏?
Answer 1:
Option 1
If you haven't fetched the collection yet, you can fetch the first one, then fetch the second one with the {add : true} flag and the second one will be merged into the first one:
collection.fetch({data : {page : 2});
=> [{id: 1, article : "..."}, {id: 2, article : "..."}];
collection.fetch({data : {page : 2}, add : true });
=> [{id: 1, article : "..."}, {id: 2, article : "..."}, {id: 3, article : "..."}];
Option 2
If you've already fetched the collections and have them stored in two variables, you can just add all contents of the second collection into the first one:
collection1.add(collection2.toJSON());
This options suffers from the fact that the first collection will fire the "add" event when the second collection is added to it. If this has side effects such as undesired UI that re-renders due to this event, you can suppress it by adding the {silent : true} flag
collection1.add(collection2.toJSON(), {silent : true});
Option 3
If you just need the JSON format of these collections, i.e. for HTML template rendering purposes, you can just reduce everything to JS literals (arrays, objects):
collection1.toJSON().concat(collection2.toJSON());
=> [{id: 1, article : "..."}, {id: 2, article : "..."}, ...];
Option 4 = Option 2 + 3
If you've already fetched both collections, you can reduce to JS literals and add everything to a fresh Backbone collection
var rawCollection = collection1.toJSON().concat(collection2.toJSON());
var newCollection = new Backbone.Collection(rawCollection);
Answer 2:
试试这个,收集的车型阵列
collection1.add(collection2.models);
如果我们使用
collection1.add(collection2.toJSON());
然后引用CHAGE
Answer 3:
collection.add(models, [options])
收藏是模型数组
collection.models
返回的车型阵列
一个模型(或模型数组)添加到集合中。
A = Backbone.Collection;
collection1 = new A([
{key, 'value'}, //model1
{key : value1} //model2 in collection1
]);
B = Backbone.Collection;
collection2 = new B([
{key1, 'value'}, //model1
{key1 : value1} //model2 in collection2
]);
collection1.add(collection2.models); //now, collection1 has four models..
Answer 4:
使用
collection.models
的insted的
collection.toJSON()
Answer 5:
在我看来,通过这样做,你就失去了语义绑/api/page/{1, 2}/
。
它还在我看来,无论是骨干网,既没有下划线,为您提供了一个函数/方法做的正是你想要做什么。
所以,你的选择:
- 创建一个新的集合,从以前的集合添加每个项目;
- 添加第一个集合项目的第二个
但你可能已经知道这一点。
Answer 6:
Collection.models提供moels和Collection.add的阵列直接访问将采取的模式数组作为参数。