javascript - Backbone - Merge 2 Collections together? -


suppose there 2 collections, representing respectively /api/page/1 , /api/page/2; there anyway (through underscore, example) merge these 2 collections new, single collection?

option 1

if haven't fetched collection yet, can fetch first one, fetch second 1 {add : true} flag , second 1 merged 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 fetched collections , have them stored in 2 variables, can add contents of second collection first one:

collection1.add(collection2.tojson()); 

this options suffers fact first collection fire "add" event when second collection added it. if has side effects such undesired ui re-renders due event, can suppress adding {silent : true} flag

collection1.add(collection2.tojson(), {silent : true}); 

option 3

if need json format of these collections, i.e. html template rendering purposes, can reduce js literals (arrays, objects):

collection1.tojson().concat(collection2.tojson()); => [{id: 1, article : "..."}, {id: 2, article : "..."}, ...]; 

option 4 = option 2 + 3

if you've fetched both collections, can reduce js literals , add fresh backbone collection

var rawcollection = collection1.tojson().concat(collection2.tojson()); var newcollection = new backbone.collection(rawcollection); 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -