Backbone multiple collections fetch from a single big JSON file
Asked Answered
M

5

12

I would like to know if any better way to create multiple collections fetching from a single big JSON file. I got a JSON file looks like this.

{
  "Languages": [...],
  "ProductTypes": [...],
  "Menus": [...],
  "Submenus": [...],
  "SampleOne": [...],
  "SampleTwo": [...],
  "SampleMore": [...]
}

I am using the url/fetch to create each collection for each node of the JSON above.

var source = 'data/sample.json'; 

Languages.url = source;
Languages.fetch();

ProductTypes.url = source;
ProductTypes.fetch();

Menus.url = source;
Menus.fetch();

Submenus.url = source;
Submenus.fetch();

SampleOne.url = source;
SampleOne.fetch();

SampleTwo.url = source;
SampleTwo.fetch();

SampleMore.url = source;
SampleMore.fetch();

Any better solution for this?

Maharani answered 20/3, 2012 at 3:48 Comment(0)
P
18

Backbone is great for when your application fits the mold it provides. But don't be afraid to go around it when it makes sense for your application. It's a very small library. Making repetitive and duplicate GET requests just to fit backbone's mold is probably prohibitively inefficient. Check out jQuery.getJSON or your favorite basic AJAX library, paired with some basic metaprogramming as following:

//Put your real collection constructors here. Just examples.
var collections = {
    Languages: Backbone.Collection.extend(),
    ProductTypes: Backbone.Collection.extend(),
    Menus: Backbone.Collection.extend()
};

function fetch() {
    $.getJSON("/url/to/your/big.json", {
        success: function (response) {
            for (var name in collections) {
                //Grab the list of raw json objects by name out of the response
                //pass it to your collection's constructor
                //and store a reference to your now-populated collection instance
                //in your collection lookup object
                collections[name] = new collections[name](response[name]);
            }
        }
    });
}

fetch();

Once you've called fetch() and the asyn callback has completed, you can do things like collections.Menus.at(0) to get at the loaded model instances.

Peking answered 20/3, 2012 at 4:40 Comment(0)
P
14

Your current approach, in addition to being pretty long, risks retrieving the large file multiple times (browser caching won't always work here, especially if the first request hasn't completed by the time you make the next one).

I think the easiest option here is to go with straight jQuery, rather than Backbone, then use .reset() on your collections:

$.get('data/sample.json', function(data) {
    Languages.reset(data['Languages']);
    ProductTypes.reset(data['ProductTypes']);
    // etc
});

If you wanted to cut down on the redundant code, you can put your collections into a namespace like app and then do something like this (though it might be a bit too clever to be legible):

app.Languages = new LanguageCollection();
// etc

$.get('data/sample.json', function(data) {
    _(['Languages', 'ProductTypes', ... ]).each(function(collection) {
        app[collection].reset(data[collection]);
    })
});
Phenetidine answered 20/3, 2012 at 4:40 Comment(0)
C
6

I think you can solve your need and still stay into the Backbone paradigm, I think an elegant solution that fits to me is create a Model that fetch the big JSON and uses it to fetch all the Collections in its change event:

var App = Backbone.Model.extend({
  url: "http://myserver.com/data/sample.json",

  initialize: function( opts ){
    this.languages    = new Languages();
    this.productTypes = new ProductTypes();
    // ...

    this.on( "change", this.fetchCollections, this );
  },

  fetchCollections: function(){
    this.languages.reset( this.get( "Languages" ) );
    this.productTypes.reset( this.get( "ProductTypes" ) );
    // ...
  }
});

var myApp = new App();
myApp.fetch();

You have access to all your collections through:

myApp.languages
myApp.productTypes
...
Corinthians answered 20/3, 2012 at 9:26 Comment(1)
Whilst the model abstraction is quite appealing I don't like this approach. The data is never going to be stored in it's current structure ... it's going to be split up into different collections. You might as well just use .json(). The purpose of a model is to store 'something' right?Jerlenejermain
C
4

You can easily do this with a parse method. Set up a model and create an attribute for each collection. There's nothing saying your model attribute has to be a single piece of data and can't be a collection.

When you run your fetch it will return back the entire response to a parse method that you can override by creating a parse function in your model. Something like:

parse: function(response) {
    var myResponse = {};
    _.each(response.data, function(value, key) {
        myResponse[key] = new Backbone.Collection(value);
    }

    return myResponse;
}

You could also create new collections at a global level or into some other namespace if you'd rather not have them contained in a model, but that's up to you.

To get them from the model later you'd just have to do something like:

model.get('Languages');
Ciera answered 20/3, 2012 at 4:57 Comment(1)
Our server gives me massively nested objects at I unwrap in parse and add to collections as necessary.Slipknot
R
0

backbone-relational provides a solution within backbone (without using jQuery.getJSON) which might make sense if you're already using it. Short answer at https://mcmap.net/q/909613/-bootstrapping-data-with-backbone-using-one-query-as-opposed-to-multiple-queries which I'd be happy to elaborate on if needed.

Recti answered 19/6, 2012 at 6:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.