Possible to do a general Backbone.js fetch to fill multiple collections? [Backbone.js/Express]

Possible to do a general Backbone.js fetch to fill multiple collections? [Backbone.js/Express]

Problem

I have a page which uses multiple collections(6 or so), each collection needing to fetch data from the server when the page is routed to. Obviously, there a lot of connections that need to happen which will probably make this page slow. I was wondering if a general fetch is possible when I route to this page. This way I can retrieve all the data at once, send it as one big json chunk, and allocate the data to each collection at the same time. This would take only one connection. I looked around and did not see such a technique for Backbone.

Is this is proper thought? I am using Express/Node on the server side.

Thanks

Problem courtesy of: Irlanco

Solution

I can’t comment of whether or not this is good, but I have done something similar. I simply made an AJAX request using jQuery to my endpoint which served the data for all the collections in one large JSON object, similar to:

{
    "Collection1": [...],
    "Collection2": [...],
    ....
    "CollectionN": [...]
}

When I get the response from the server (in the success callback) I take the data for each collection and just use the collection.add() function. This is basically the same as what Backbone does in fetch (make the request, and pass the returned values into add). When an array is passed to the collection.add() function each object in the array is used to create a a model.

Solution courtesy of: Nick Mitchinson

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *