Skip to content

Commit

Permalink
events: don't delete the listeners array
Browse files Browse the repository at this point in the history
The documentation implies that .removeAllListeners() leaves the listeners array
untouched. Make it so.
  • Loading branch information
bnoordhuis committed Mar 15, 2012
1 parent f9aa01d commit 78dc13f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
11 changes: 9 additions & 2 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,15 @@ EventEmitter.prototype.removeAllListeners = function(type) {
return this;
}

// does not use listeners(), so no side effect of creating _events[type]
if (type && this._events && this._events[type]) this._events[type] = null;
var events = this._events && this._events[type];
if (!events) return this;

if (isArray(events)) {
events.splice(0);
} else {
this._events[type] = null;
}

return this;
};

Expand Down
10 changes: 7 additions & 3 deletions test/simple/test-event-emitter-remove-all-listeners.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,14 @@ function listener() {}
var e1 = new events.EventEmitter();
e1.on('foo', listener);
e1.on('bar', listener);
var fooListeners = e1.listeners('foo');
var barListeners = e1.listeners('bar');
e1.removeAllListeners('foo');
assert.deepEqual([], e1.listeners('foo'));
assert.deepEqual([listener], e1.listeners('bar'));

assert.deepEqual(e1.listeners('foo'), []);
assert.deepEqual(e1.listeners('bar'), [listener]);
// identity check, the array should not change
assert.equal(e1.listeners('foo'), fooListeners);
assert.equal(e1.listeners('bar'), barListeners);

var e2 = new events.EventEmitter();
e2.on('foo', listener);
Expand Down

0 comments on commit 78dc13f

Please sign in to comment.