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?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
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:
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:
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
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):
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
use
insted of
try this, collection is array of models
if we use
then reference chage
Collection.models provides direct access to the array of moels and Collection.add will take an array of models as an argument.
Collection is array of models
returns array of models
Add a model (or an array of models) to the collection.
It seems to me that by doing this, you lose the semantic tied to
/api/page/{1, 2}/
.It also seems to me that neither backbone, neither underscore, provides you with a function/method doing exactly what you're trying to do.
So your options :
But you probably already knew this.