Skip to content

Commit

Permalink
fix adding events which have same names with methods of Object
Browse files Browse the repository at this point in the history
  • Loading branch information
nkzawa authored and jonathanong committed Feb 12, 2015
1 parent 7abd6b0 commit b34d74c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
10 changes: 5 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ function mixin(obj) {
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
(this._callbacks['$' + event] = this._callbacks['$' + event] || [])
.push(fn);
return this;
};
Expand Down Expand Up @@ -91,12 +91,12 @@ Emitter.prototype.removeEventListener = function(event, fn){
}

// specific event
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 @@ -123,7 +123,7 @@ Emitter.prototype.removeEventListener = function(event, fn){
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
, callbacks = this._callbacks['$' + event];

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

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

/**
Expand Down
18 changes: 18 additions & 0 deletions test/emitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,24 @@ describe('Emitter', function(){

calls.should.eql([ 'one', 1, 'two', 1, 'one', 2, 'two', 2 ]);
})

it('should add listeners for events which are same names with methods of Object.prototype', function(){
var emitter = new Emitter;
var calls = [];

emitter.on('constructor', function(val){
calls.push('one', val);
});

emitter.on('__proto__', function(val){
calls.push('two', val);
});

emitter.emit('constructor', 1);
emitter.emit('__proto__', 2);

calls.should.eql([ 'one', 1, 'two', 2 ]);
})
})

describe('.once(event, fn)', function(){
Expand Down

0 comments on commit b34d74c

Please sign in to comment.