From b34d74c7aeef326eeb452a3713b06ad20f92ebb4 Mon Sep 17 00:00:00 2001 From: Naoyuki Kanezawa Date: Fri, 13 Feb 2015 02:15:10 +0900 Subject: [PATCH] fix adding events which have same names with methods of Object --- index.js | 10 +++++----- test/emitter.js | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index 6c45592..1c78176 100644 --- a/index.js +++ b/index.js @@ -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; }; @@ -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; } @@ -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); @@ -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] || []; }; /** diff --git a/test/emitter.js b/test/emitter.js index 91ea483..02c3a0b 100644 --- a/test/emitter.js +++ b/test/emitter.js @@ -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(){