Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to initialise a backbone Collection with object IDs rather than objects?

I have a Backbone.js Collection and I have an array of model IDs that I want to populate it. I know that I could fetch these objects one by one, build an array of objects and pass them into the Collection's constructor as an array.

What I'd like to be able to do is pass the array of object ids into the constructor as initial data, and get the Collection to fetch them, possibly as batch, as per this.

Doable?

like image 287
Joe Avatar asked Aug 03 '11 18:08

Joe


People also ask

What is collections in Backbone JS?

A Backbone. js Collections are a group of related models. It is useful when the model is loading to the server or saving to the server. Collections also provide a helper function for performing computation against a list of models.

Does Backbone require jQuery?

You can use the Backbone. Model without jQuery, but Backbone. View will require either jQuery or Zepto, just like the docs state. Chances of not using view and router is low enough.

What is Backbone used for?

It is designed for developing single-page web applications, and for keeping various parts of web applications (e.g. multiple clients and the server) synchronized. Backbone was created by Jeremy Ashkenas, who is also known for CoffeeScript and Underscore. js.


1 Answers

When you call 'fetch' on a Backbone.Collection, it in turn calls Backbone.sync, which by default just asks the collection for the url to use.

So if your server responds to:

/models/batch/?ids=1,2,3,4

You could do something like:

var MyCollection = Backbone.Collection.extend({

    model: Model,

    url: '/models',

    initialize: function(models, options) {
        ids = options.ids || [];
        if (ids.length > 0) { 
            this.fetchByIds(ids);
        }
    },

    fetchByIds: function(ids) {
        // Save a reference to the existing url
        var baseUrl = this.url;

        // Assign our batch url to the 'url' property and call the server
        this.url += '/?ids=' + ids.join(',');
        this.fetch();

        // Restore the 'url' property
        this.url = baseUrl;
    }
});

And use it like so:

var coll = new MyCollection({}, {ids: [1, 2, 3, 4]});

You'd have to pass the ids in the options parameter, because the Backbone.Collection constructor function sets the models passed in the first parameter before it calls the 'initialize' function.

Theoretically, this should work (read: completely untried).

like image 53
satchmorun Avatar answered Sep 20 '22 16:09

satchmorun