Skip to content

Instantly share code, notes, and snippets.

@luggage66
Last active September 3, 2015 17:06
Show Gist options
  • Save luggage66/03647d695520d03597e7 to your computer and use it in GitHub Desktop.
Save luggage66/03647d695520d03597e7 to your computer and use it in GitHub Desktop.
function onceAll(events, callback) {
var eventState = Object.create(null);
// argument `events` is expected to be an array of event names.
events.forEach((eventName) => {
// Initil state: { event1: false, event2: false }
eventState[eventName] = false;
// for each event, register a handler that updates the state and checks if we are 'done' yet
this.once(eventName, () =>
//mark it true when called once
eventState[eventName] = true;
//are all events called, yet?
if (events.every((eventName) => eventState[eventName])) {
callback(); //success!
}
});
});
}
Backbone.model.prototype.onceAll = onceAll; //or some other way to get this on there.
function onceAll(events, callback) {
var backboneObject = this;
var eventState = Object.create(null);
// argument `events` is expected to be an array of event names.
events.forEach(function(eventName) {
// Initil state: { event1: false, event2: false }
eventState[eventName] = false;
// for each event, register a handler that updates the state and checks if we are 'done' yet
// This is an IIFE to make sure 'eventName' is correct for each iteration of the loop
(backboneObject.once(eventName, function() {
//mark it true when called once
eventState[eventName] = true;
//are all events called, yet?
if (events.every(function(eventName) { return eventState[eventName]; })) {
callback(); //success!
}
}))(eventName);
});
}
Backbone.model.prototype.onceAll = onceAll; //or some other way to get this on there.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment