I think the way to override fetch is where you make an Ajax call to each of the APIs. Store the returned partial sets in a temporary array, and when all 4 are complete, create a collection using this.reset . (You can use jQuery Deferred , I suppose, or just keep an internal account of how many calls were returned.)
Something like that:
var Collection = Backbone.Collection.extend({ fetch: function() { this.completeCount = 0; this.errorCount = 0; this.temp = []; this.urls = [ 'url1', 'url2', 'url3', 'url4' ]; var self = this; // make a $.get call for each URL and add _.each(this.urls, function(url) { $.get(url, { success: function(data) { console.log("Got partial collection from " + url); self.addPartial(data); // alternatively, just call "self.add(data);" here }, error: function(response) { console.log("Oops, the Ajax call failed for some reason... ignoring"); self.completeCount ++; self.errorCount ++; } }); }); }, // add a JSON array that contains a subset of the collection addPartial: function(data) { this.completeCount ++; var self = this; // add each item to temp _.each(data, function(item) { self.temp.push(item); }); // if all have been received, then create the collection if (this.completeCount == this.urls.length) { this.reset(this.temp); } } });
Here's a scenario where I replaced $.get with a method that simply returns dummy data after a short delay.
Reply to comment
Adding answers to the collection as they become available is probably better (itās easier anyway). Fiddle updated here.
source share