Skip to content

Commit

Permalink
add this._callbacks initialization to prevent funky gotcha
Browse files Browse the repository at this point in the history
  • Loading branch information
tj committed Oct 9, 2012
1 parent d4919f1 commit c3fc7f5
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 7 deletions.
5 changes: 0 additions & 5 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
7 changes: 5 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ module.exports = Emitter;

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

/**
Expand All @@ -25,7 +24,6 @@ function Emitter(obj) {
*/

function mixin(obj) {
obj._callbacks = {};
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
Expand All @@ -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;
Expand All @@ -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);
Expand All @@ -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;

Expand All @@ -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];

Expand All @@ -127,6 +129,7 @@ Emitter.prototype.emit = function(event){
*/

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

Expand Down

0 comments on commit c3fc7f5

Please sign in to comment.