Skip to content

Instantly share code, notes, and snippets.

@muit
Created August 6, 2015 10:51
Show Gist options
  • Select an option

  • Save muit/312eda2f0af64a6fc20b to your computer and use it in GitHub Desktop.

Select an option

Save muit/312eda2f0af64a6fc20b to your computer and use it in GitHub Desktop.
/**
* Wait for x events to finish, and then call a function.
* @param {Array} ids [Registered event ids]
*/
function EventWaiter(ids){
if(names instanceof Array) {
this.waitEvents = ids;
}
}
EventWaiter.prototype = {
waitEvents: [],
callback: undefined,
/**
* Registry a new event
* @param {Anything} id [Id of the new event]
* @return {bool} [Existed already?]
*/
registry: function(id){
if(this.names.indexOf(id) == -1) {
this.waitEvents.push(id);
return false;
}
return true;
}
/**
* Called when a event finished
* @param {Anything} id [Id of the finished event]
* @return {bool} [Did the EventWaiter finished?]
*/
call: function(id){
remove(this.waitEvents, id);
if(this.waitEvents.length <= 0 && this.callback){
this.callback();
this.callback = undefined;
return true;
}
return false;
},
/**
* Set the function to be called when the EventWaiter finishes
* @param {Function} callback
*/
then: function(callback){
this.callback = callback;
},
}
function remove(array, element){
var index = array.indexOf(element);
if (index > -1) {
array.splice(index, 1);
}
}
// Example
eventWaiter = new EventWaiter(["bailar", "cantar", "comer"]);
bailar(function(){
eventWaiter.call("bailar");
});
cantar(function(){
eventWaiter.call("cantar");
});
comer(function(){
eventWaiter.call("comer");
});
eventWaiter.then(function(){
console.log("Finish");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment