Skip to content

Commit

Permalink
lib: fix TypeError with EventEmitter#on() abuse
Browse files Browse the repository at this point in the history
Commit 2931348 added EventEmitter#getMaxListeners() but introduced a
regression when people abuse EventEmitter.prototype.on.call() to call
EventEmitter#on() on a non-EE object.  Add a workaround for that.

Fixes: #523
PR-URL: #527
Reviewed-By: Colin Ihrig <[email protected]>
  • Loading branch information
bnoordhuis committed Jan 20, 2015
1 parent 77d6807 commit ee9cd00
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
13 changes: 8 additions & 5 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,14 @@ EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
return this;
};

EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
if (!util.isUndefined(this._maxListeners))
return this._maxListeners;
else
function $getMaxListeners(that) {
if (util.isUndefined(that._maxListeners))
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}

EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return $getMaxListeners(this);
};

EventEmitter.prototype.emit = function emit(type) {
Expand Down Expand Up @@ -151,7 +154,7 @@ EventEmitter.prototype.addListener = function addListener(type, listener) {

// Check for listener leak
if (util.isObject(this._events[type]) && !this._events[type].warned) {
var m = this.getMaxListeners();
var m = $getMaxListeners(this);
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
Expand Down
5 changes: 5 additions & 0 deletions test/parallel/test-event-emitter-get-max-listeners.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,8 @@ assert.strictEqual(emitter.getMaxListeners(), 0);

emitter.setMaxListeners(3);
assert.strictEqual(emitter.getMaxListeners(), 3);

// https://github.com/iojs/io.js/issues/523 - second call should not throw.
var recv = {};
EventEmitter.prototype.on.call(recv, 'event', function() {});
EventEmitter.prototype.on.call(recv, 'event', function() {});

0 comments on commit ee9cd00

Please sign in to comment.