Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone - Merge 2 Collections together?

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?

like image 986
gsklee Avatar asked Sep 12 '12 08:09

gsklee


1 Answers

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); 
like image 167
Gur Dotan Avatar answered Oct 09 '22 09:10

Gur Dotan