Created
May 4, 2013 13:45
-
-
Save pierreis/5517562 to your computer and use it in GitHub Desktop.
Javascript minimalist EventEmitter.
This file contains hidden or 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
/** | |
* `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