Skip to content

Instantly share code, notes, and snippets.

@danprince
Created September 1, 2014 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danprince/26a68cfa664018aa29a9 to your computer and use it in GitHub Desktop.
Save danprince/26a68cfa664018aa29a9 to your computer and use it in GitHub Desktop.
Generic Event Emitter
module.exports = function() {
var handlers = {};
function _register(name) {
return handlers[name] || handlers[name] = [];
}
function on(name, handler) {
var event = _register(name);
event.push(handler);
}
function off(name, handler) {
var event, index;
event = _register(name);
index = event.indexOf(handler);
if(index > -1) {
event.splice(index, 1);
}
}
function emit(name, data) {
var args, events, index;
args = [].slice.call(arguments, 1);
events = _register(name);
for(index = 0; index < events.length; index++) {
events[i].apply(events[i], args);
}
}
return {
on: on,
off: off,
emit: emit
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment