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?
If you're using jQuery, use when
:
$.when(collA.fetch(),collB.fetch()).done(function(){ //success code here. });
Background:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With