Skip to content

Instantly share code, notes, and snippets.

@pierreis
Created May 4, 2013 13:45
Show Gist options
  • Save pierreis/5517562 to your computer and use it in GitHub Desktop.
Save pierreis/5517562 to your computer and use it in GitHub Desktop.
Javascript minimalist EventEmitter.
/**
* `Emitter` constructor.
*/
var Emitter = module.exports = function Emitter() {
this.callbacks = {};
};
/**
* `Emitter` prototype.
*/
Emitter.prototype = {
callback: function callback(event, cb, once) {
(this.callbacks[event] = this.callbacks[event] || []).push([cb, !!once]);
return this;
},
on: function on(event, callback) {
return this.callback(event, callback, false);
},
once: function once(event, callback) {
return this.callback(event, callback, true);
},
emit: function emit(event) {
var args = Array.prototype.slice.call(arguments, 1);
var newCallbacks = [];
var ok = true;
(tthis.callbacks[event] || []).forEach(function (item) {
ok = ok && item[0].apply(undefined, args) !== false;
item[1] || newCallbacks.push(item);
});
this.callbacks[event] = newCallbacks;
return ok;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment