Skip to content

Commit

Permalink
events: pass the original listener added by once
Browse files Browse the repository at this point in the history
When removing a `once` listener, the listener being passed to
the `removeListener` callback is the wrapper. This unwraps the
listener so that `removeListener` is passed the actual listener.

PR-URL: #6394
Reviewed-By: Colin Ihrig <[email protected]>
Reviewed-By: James M Snell <[email protected]>
  • Loading branch information
DavidCai1111 authored and Myles Borins committed Nov 22, 2016
1 parent 96bdfae commit f6f0b38
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
7 changes: 4 additions & 3 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ EventEmitter.prototype.once = function once(type, listener) {
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i;
var list, events, position, i, originalListener;

if (typeof listener !== 'function')
throw new TypeError('listener must be a function');
Expand All @@ -289,14 +289,15 @@ EventEmitter.prototype.removeListener =
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, listener);
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;

for (i = list.length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
originalListener = list[i].listener;
position = i;
break;
}
Expand All @@ -318,7 +319,7 @@ EventEmitter.prototype.removeListener =
}

if (events.removeListener)
this.emit('removeListener', type, listener);
this.emit('removeListener', type, originalListener || listener);
}

return this;
Expand Down
11 changes: 11 additions & 0 deletions test/parallel/test-event-emitter-remove-listeners.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,14 @@ e6.emit('hello');

// Interal listener array [listener3]
e6.emit('hello');

const e7 = new events.EventEmitter();

const listener5 = () => {};

e7.once('hello', listener5);
e7.on('removeListener', common.mustCall((eventName, listener) => {
assert.strictEqual(eventName, 'hello');
assert.strictEqual(listener, listener5);
}));
e7.emit('hello');

0 comments on commit f6f0b38

Please sign in to comment.