Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed May 2, 2012
0 parents commit 709deff
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 0 deletions.
100 changes: 100 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -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;
};
10 changes: 10 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "emitter",
"description": "Event emitter",
"version": "0.0.1",
"component": {
"scripts": {
"emitter": "index.js"
}
}
}

0 comments on commit 709deff

Please sign in to comment.