Skip to content

Commit

Permalink
add mixin support via Emitter(obj). Closes sindresorhus#5
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed Sep 6, 2012
1 parent 01f8365 commit b251af6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
31 changes: 24 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,27 @@ module.exports = Emitter;
* @api public
*/

function Emitter() {
this.callbacks = {};
function Emitter(obj) {
if (!(this instanceof Emitter)) return mixin(obj);
this._callbacks = {};
};

/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/

function mixin(obj) {
obj._callbacks = {};
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}

/**
* Listen on the given `event` with `fn`.
*
Expand All @@ -25,7 +42,7 @@ function Emitter() {
*/

Emitter.prototype.on = function(event, fn){
(this.callbacks[event] = this.callbacks[event] || [])
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
Expand Down Expand Up @@ -64,12 +81,12 @@ Emitter.prototype.once = function(event, fn){
*/

Emitter.prototype.off = function(event, fn){
var callbacks = this.callbacks[event];
var callbacks = this._callbacks[event];
if (!callbacks) return this;

// remove all handlers
if (1 == arguments.length) {
delete this.callbacks[event];
delete this._callbacks[event];
return this;
}

Expand All @@ -89,7 +106,7 @@ Emitter.prototype.off = function(event, fn){

Emitter.prototype.emit = function(event){
var args = [].slice.call(arguments, 1)
, callbacks = this.callbacks[event];
, callbacks = this._callbacks[event];

if (callbacks) {
callbacks = callbacks.slice(0);
Expand All @@ -110,7 +127,7 @@ Emitter.prototype.emit = function(event){
*/

Emitter.prototype.listeners = function(event){
return this.callbacks[event] || [];
return this._callbacks[event] || [];
};

/**
Expand Down
9 changes: 9 additions & 0 deletions test/emitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,12 @@ describe('Emitter', function(){
})
})
})

describe('Emitter(obj)', function(){
it('should mixin', function(done){
var proto = {};
Emitter(proto);
proto.on('something', done);
proto.emit('something');
})
})

0 comments on commit b251af6

Please sign in to comment.