Backbone - Merge 2 Collections together?

后端 未结 6 1823
灰色年华
灰色年华 2020-12-23 23:17

Suppose there are 2 Collections, representing respectively /api/page/1 and /api/page/2; is there anyway (through Underscore, for example) to merge

6条回答
  •  难免孤独
    2020-12-23 23:39

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

提交回复
热议问题