骨干 - 将2个集合合并在一起?

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)

  • -1.如果调用toJSON(),则会丢失对模型的引用.如果创建模型,将其插入集合,将集合与另一个集合,更改模型,则不会更新最后一个集合中的模型.这将成为调试的噩梦.如果您想复制模型并将它们分开,那就没关系,但这不是常态,应该指出. (12认同)
  • 如果你已经拥有这两个集合,你可能应该使用下面的任何答案:`collection1.add(collection2.models);` (9认同)
  • 虽然可以奏效,但整体答案却颇具误导性.真正的答案:_collection1.add(collection2.models); _如下所述:http://backbonejs.org/#Collection-add (3认同)

小智 41

试试这个,集合是一系列模型

collection1.add(collection2.models); 
Run Code Online (Sandbox Code Playgroud)

如果我们使用

 collection1.add(collection2.toJSON());
Run Code Online (Sandbox Code Playgroud)

然后参考chage

  • +1这是唯一真正的答案,应该是真正的答案.请参阅文档:http://backbonejs.org/#Collection-add.您还可以通过传递来决定是否接受重复项:{merge:true} (6认同)

Arr*_*und 5

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)