Skip to content

Instantly share code, notes, and snippets.

@webjay
Created July 31, 2014 23:02
Show Gist options
  • Save webjay/fe4ddb5b93e037bc9bbe to your computer and use it in GitHub Desktop.
Save webjay/fe4ddb5b93e037bc9bbe to your computer and use it in GitHub Desktop.
How to listen to an event on multiple objects using Backbone.js
function whenAll (objects, event, callback) {
var callbackWrapper = _.after(objects.length, callback);
_.each(objects, function (obj) {
obj.once(event, callbackWrapper, this);
}, this);
}
@webjay
Copy link
Author

webjay commented Jul 31, 2014

Inspired by How to listen to an event on multiple objects using Backbone.js.

I use it like this:

preload: function (callback) {
  var collections = [users, messages];
  whenAll(collections, 'sync', callback);
  for (var i = collections.length - 1; i >= 0; i--) {
    collections[i].fetch();
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment