gsk*_*lee 27 javascript backbone.js
假设有2个类别,分别代表/api/page/1和/api/page/2; 无论如何(通过Underscore)将这两个集合合并为一个新的单一集合?
小智 49
选项1
如果你还没有提取集合,你可以获取第一个,然后使用{add:true}标志获取第二个,第二个将合并到第一个:
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 : "..."}];
Run Code Online (Sandbox Code Playgroud)
选项2
如果您已经获取了集合并将它们存储在两个变量中,则只需将第二个集合的所有内容添加到第一个集合中:
collection1.add(collection2.toJSON());
Run Code Online (Sandbox Code Playgroud)
这个选项会受到以下事实的影响:第一个集合将在添加第二个集合时触发"add"事件.如果这有副作用,例如由于此事件而重新渲染的不需要的UI,您可以通过添加{silent:true}标志来抑制它
collection1.add(collection2.toJSON(), {silent : true});
Run Code Online (Sandbox Code Playgroud)
选项3
如果您只需要这些集合的JSON格式,即用于HTML模板呈现,您可以将所有内容减少为JS文字(数组,对象):
collection1.toJSON().concat(collection2.toJSON());
=> [{id: 1, article : "..."}, {id: 2, article : "..."}, ...];
Run Code Online (Sandbox Code Playgroud)
选项4 =选项2 + 3
如果您已经获取了两个集合,则可以减少JS文字并将所有内容添加到新的Backbone集合中
var rawCollection = collection1.toJSON().concat(collection2.toJSON());
var newCollection = new Backbone.Collection(rawCollection);
Run Code Online (Sandbox Code Playgroud)
小智 41
试试这个,集合是一系列模型
collection1.add(collection2.models);
Run Code Online (Sandbox Code Playgroud)
如果我们使用
collection1.add(collection2.toJSON());
Run Code Online (Sandbox Code Playgroud)
然后参考chage
collection.add(models, [options])
Run Code Online (Sandbox Code Playgroud)
集合是一系列模型
collection.models
Run Code Online (Sandbox Code Playgroud)
返回模型数组
将模型(或模型数组)添加到集合中.
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..
Run Code Online (Sandbox Code Playgroud)
小智 5
使用
collection.models
Run Code Online (Sandbox Code Playgroud)
绝对的
collection.toJSON()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18332 次 |
| 最近记录: |