主干 - 合并2集合在一起吗? [英] Backbone - Merge 2 Collections together?

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

问题描述

假设有2个类别,再presenting分别为 / API /页/ 1 / API /页/ 2 ;反正是有(通过下划线,例如)这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

如果您还没有获取的收集是,你可以获取第一个,然后取第二个用{补充:真}标志,第二个将被合并到第一个:

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重新呈现由于此事件,您可以通过添加{沉默:真燮} preSS它标志

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

如果您只是需要这些集合,即对于HTML模板渲染目的的JSON格式,你可以事事减少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文字,并添加一切到一个新的集合骨干

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

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

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