From 709deff363e9622eac87a5dc3301e6890c9f5fff Mon Sep 17 00:00:00 2001 From: TJ Holowaychuk Date: Wed, 2 May 2012 10:44:33 -0700 Subject: [PATCH] Initial commit --- index.js | 100 +++++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 10 ++++++ 2 files changed, 110 insertions(+) create mode 100644 index.js create mode 100644 package.json diff --git a/index.js b/index.js new file mode 100644 index 0000000..972dd4e --- /dev/null +++ b/index.js @@ -0,0 +1,100 @@ + +/** + * Expose `Emitter`. + */ + +module.exports = Emitter; + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter() { + this.callbacks = {}; +}; + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = function(event, fn){ + (this.callbacks[event] = this.callbacks[event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + var self = this; + + function on() { + self.off(event, on); + fn.apply(this, arguments); + } + + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = function(event, fn){ + var callbacks = this.callbacks[event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this.callbacks[event]; + return this; + } + + // remove specific handler + var i = callbacks.indexOf(fn); + callbacks.splice(i, 1); + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + var args = [].slice.call(arguments, 1) + , callbacks = this.callbacks[event]; + + if (callbacks) { + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..7c4d89b --- /dev/null +++ b/package.json @@ -0,0 +1,10 @@ +{ + "name": "emitter", + "description": "Event emitter", + "version": "0.0.1", + "component": { + "scripts": { + "emitter": "index.js" + } + } +}