Extract data from different urls using the same collection in js trunk

I have a collection that should call 4 external apis Eg: http://www.abc.com , http://www.fgt.com , http://www.jkl.com and http: //www.rty .com .

I have a collection called Todos.js. Is there a way that I can put 4 apis together in one collection, since all four apis provided me with the same model response Thus, the answer I get from 4 apis has the same data structure as the "name" and "link".

Is there a way to add all the answers in one collection? What is the best way to achieve this?

+4
source share
2 answers

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.

+6
source

I know this is an old question, but if someone gets here, this information may help. To save the data previously collected by the collection, you can change the URL and call the fetch () method at any time necessary for these parameters:

 reset: false, remove: false, 

Like this

 yourCollection.fetch({reset: false, remove: false, [other]: [wathever]}) 

And that’s all, you don’t need to redefine the method. (Perhaps it was necessary in 2012, dunno. The fact is that these options work for Backbone 1.1.2 or later). Keep in mind that im not sure if this will merge or just add new data, even if it will be repeated.

The documentation ( http://backbonejs.org/#Collection-fetch ) is a bit confused with the 'reset option, because it says that it is false by default, perhaps this can only be applied when the URL remains static and single.

+1
source

All Articles