Backbone - 将 2 个集合合并在一起? [英] Backbone - Merge 2 Collections together?

查看:20
本文介绍了Backbone - 将 2 个集合合并在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有2个Collection,分别代表/api/page/1/api/page/2;无论如何(例如通过下划线)将这两个集合合并为一个新的单个集合?

Suppose there are 2 Collections, representing respectively /api/page/1 and /api/page/2; is there anyway (through Underscore, for example) to merge these 2 Collections into a new, single Collection?

推荐答案

选项 1

如果您还没有获取集合,您可以获取第一个集合,然后使用 {add : true} 标志获取第二个集合,第二个将合并到第一个中:

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 : "..."}];

选项 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());

这个选项受到这样一个事实的影响,即第一个集合将在第二个集合添加到它时触发添加"事件.如果这有副作用,例如由于此事件而重新渲染的不需要的 UI,您可以通过添加 {silent : true} 标志来抑制它

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});

选项 3

如果您只需要这些集合的 JSON 格式,即用于 HTML 模板渲染目的,您可以将所有内容简化为 JS 文字(数组、对象):

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 : "..."}, ...];

选项 4 = 选项 2 + 3

如果你已经获取了两个集合,你可以减少到 JS 文字并将所有东西添加到一个新的 Backbone 集合中

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);

这篇关于Backbone - 将 2 个集合合并在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆