Skip to content

Commit b251af6

Browse files
committed
add mixin support via Emitter(obj). Closes #5
1 parent 01f8365 commit b251af6

File tree

2 files changed

+33
-7
lines changed

2 files changed

+33
-7
lines changed

index.js

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,27 @@ module.exports = Emitter;
1111
* @api public
1212
*/
1313

14-
function Emitter() {
15-
this.callbacks = {};
14+
function Emitter(obj) {
15+
if (!(this instanceof Emitter)) return mixin(obj);
16+
this._callbacks = {};
1617
};
1718

19+
/**
20+
* Mixin the emitter properties.
21+
*
22+
* @param {Object} obj
23+
* @return {Object}
24+
* @api private
25+
*/
26+
27+
function mixin(obj) {
28+
obj._callbacks = {};
29+
for (var key in Emitter.prototype) {
30+
obj[key] = Emitter.prototype[key];
31+
}
32+
return obj;
33+
}
34+
1835
/**
1936
* Listen on the given `event` with `fn`.
2037
*
@@ -25,7 +42,7 @@ function Emitter() {
2542
*/
2643

2744
Emitter.prototype.on = function(event, fn){
28-
(this.callbacks[event] = this.callbacks[event] || [])
45+
(this._callbacks[event] = this._callbacks[event] || [])
2946
.push(fn);
3047
return this;
3148
};
@@ -64,12 +81,12 @@ Emitter.prototype.once = function(event, fn){
6481
*/
6582

6683
Emitter.prototype.off = function(event, fn){
67-
var callbacks = this.callbacks[event];
84+
var callbacks = this._callbacks[event];
6885
if (!callbacks) return this;
6986

7087
// remove all handlers
7188
if (1 == arguments.length) {
72-
delete this.callbacks[event];
89+
delete this._callbacks[event];
7390
return this;
7491
}
7592

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

90107
Emitter.prototype.emit = function(event){
91108
var args = [].slice.call(arguments, 1)
92-
, callbacks = this.callbacks[event];
109+
, callbacks = this._callbacks[event];
93110

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

112129
Emitter.prototype.listeners = function(event){
113-
return this.callbacks[event] || [];
130+
return this._callbacks[event] || [];
114131
};
115132

116133
/**

test/emitter.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,3 +144,12 @@ describe('Emitter', function(){
144144
})
145145
})
146146
})
147+
148+
describe('Emitter(obj)', function(){
149+
it('should mixin', function(done){
150+
var proto = {};
151+
Emitter(proto);
152+
proto.on('something', done);
153+
proto.emit('something');
154+
})
155+
})

0 commit comments

Comments
 (0)