Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone multiple collections fetch from a single big JSON file

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?

like image 792
jacksun101 Avatar asked Mar 20 '12 03:03

jacksun101


4 Answers

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.

like image 108
Peter Lyons Avatar answered Jan 01 '23 09:01

Peter Lyons


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]);
    })
});
like image 22
nrabinowitz Avatar answered Jan 01 '23 07:01

nrabinowitz


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
...
like image 23
fguillen Avatar answered Jan 01 '23 08:01

fguillen


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');
like image 31
ryanmarc Avatar answered Jan 01 '23 09:01

ryanmarc