-
-
Save MPMoughan/e22a864e4fd860c8929b87acc17a302d to your computer and use it in GitHub Desktop.
Really simple Javascript custom event system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Event = function() { | |
var self = this; | |
self.queue = {}; | |
self.fired = []; | |
return { | |
fire: function(event) { | |
var queue = self.queue[event]; | |
if (typeof queue === 'undefined') { | |
return; | |
} | |
while (queue.length) { | |
(queue.shift())(); | |
} | |
self.fired[event] = true; | |
}, | |
on: function(event, callback) { | |
if (self.fired[event] === true) { | |
return callback(); | |
} | |
if (typeof self.queue[event] === 'undefined') { | |
self.queue[event] = []; | |
} | |
self.queue[event].push(callback); | |
} | |
}; | |
}(); | |
// Basic usage | |
Event.on('counted.to::1000', function() { | |
doSomething(); | |
}); | |
for (i = 0; i <= 1000; i++) { | |
// Count to 1000... | |
} | |
Event.fire('counted.to::1000'); // doSomething() is called |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment