Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to synchronize multiple Backbone.js fetches?

Tags:

I’m a bit new to Backbone.js, but am already impressed by everything it can do for me, and am trying to learn the patterns and best practices now.

I have two collections:

var CollA = Backbone.Collection.extend({     model: ModelA,     url: '/urlA' });  var CollB = Backbone.Collection.extend({     model: ModelB,     url: '/urlB' });  var collA = new CollA; var collB = new CollB; 

When loading my app, I need to fetch both of these collections from the server, and run some bootstrap code when it’s guaranteed that both fetches have completed.

Here’s how I did it for now:

collA.fetch({success: function() {     collB.fetch({success: function() {         // run the needed code here.     }}); }}); 

This works, the needed code is guaranteed to run only after both fetches complete successfully. It is clearly inefficient though, because the fetches run serially, one after another.

What would be a better pattern to do this, to run the fetches in parallel and then run some code once both fetches have completed successfully?

like image 547
Jaanus Avatar asked Aug 28 '12 22:08

Jaanus


1 Answers

If you're using jQuery, use when:

$.when(collA.fetch(),collB.fetch()).done(function(){     //success code here. }); 

Background:

  • http://api.jquery.com/jQuery.when/
  • http://documentcloud.github.com/backbone/#Collection-fetch

You pass in one or more deferreds to $.when. It so happens that the "jqXHR" that collections return implements the promise/Deferred interface that can be combined into a new promise using $.when. The requests will essentially be concurrent (well, as much as javascript allows) and the function passed to .done will execute only when both fetches are successful.

like image 188
JayC Avatar answered Nov 04 '22 01:11

JayC