From c3fc7f5aa851278daf7b272a9c70fbd734493aca Mon Sep 17 00:00:00 2001 From: TJ Holowaychuk Date: Mon, 8 Oct 2012 17:00:09 -0700 Subject: [PATCH] add this._callbacks initialization to prevent funky gotcha --- Readme.md | 5 ----- index.js | 7 +++++-- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/Readme.md b/Readme.md index 206108c..8f5ffd6 100644 --- a/Readme.md +++ b/Readme.md @@ -21,11 +21,6 @@ var obj = {}; Emitter(obj); Emitter(User.prototype); ``` - - __Warning__: if you use `Emitter(Some.prototype)` on a prototype - you __must__ invoke `Emitter.call(this)` in the constructor to - clear the callbacks object, otherwise events will be shared - between multiple objects. ### Emitter#on(event, fn) diff --git a/index.js b/index.js index 388b0dc..8cc74ae 100644 --- a/index.js +++ b/index.js @@ -13,7 +13,6 @@ module.exports = Emitter; function Emitter(obj) { if (obj) return mixin(obj); - this._callbacks = {}; }; /** @@ -25,7 +24,6 @@ function Emitter(obj) { */ function mixin(obj) { - obj._callbacks = {}; for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } @@ -42,6 +40,7 @@ function mixin(obj) { */ Emitter.prototype.on = function(event, fn){ + this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; @@ -59,6 +58,7 @@ Emitter.prototype.on = function(event, fn){ Emitter.prototype.once = function(event, fn){ var self = this; + this._callbacks = this._callbacks || {}; function on() { self.off(event, on); @@ -81,6 +81,7 @@ Emitter.prototype.once = function(event, fn){ */ Emitter.prototype.off = function(event, fn){ + this._callbacks = this._callbacks || {}; var callbacks = this._callbacks[event]; if (!callbacks) return this; @@ -105,6 +106,7 @@ Emitter.prototype.off = function(event, fn){ */ Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; @@ -127,6 +129,7 @@ Emitter.prototype.emit = function(event){ */ Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; };