Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
66
rated 0 times [  72] [ 6]  / answers: 1 / hits: 19410  / 13 Years ago, wed, august 3, 2011, 12:00:00

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?


More From » backbone.js

 Answers
80

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).


[#90836] Tuesday, August 2, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxinec

Total Points: 117
Total Questions: 116
Total Answers: 116

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
;