Skip to content

Commit 9e33450

Browse files
committed
doc: emitter.removeListener clarification
Fix based on nodejs#4764 by @drjokepu. Fixes: nodejs#4759
1 parent 773b901 commit 9e33450

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

doc/api/events.markdown

+26
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,32 @@ listener array. If any single listener has been added multiple times to the
377377
listener array for the specified `event`, then `removeListener` must be called
378378
multiple times to remove each instance.
379379

380+
Please notice that a listener removed from an event *from within the emit cycle of that event* will still be called in that emit cycle:
381+
382+
```js
383+
const EventEmitter = require('events');
384+
const emitter = new EventEmitter();
385+
386+
function first() {
387+
console.log('first! this will always be called.');
388+
emitter.removeListener('test', second);
389+
}
390+
391+
function second() {
392+
console.log('second! this will only be called once in this context.');
393+
}
394+
395+
emitter.on('test', first);
396+
emitter.on('test', second);
397+
398+
emitter.emit('test');
399+
// first! this will always be called.
400+
// second! this will only be called once in this context.
401+
402+
emitter.emit('test');
403+
// first! this will always be called.
404+
```
405+
380406
Because listeners are managed using an internal array, calling this will
381407
change the position indices of any listener registered *after* the listener
382408
being removed. This will not impact the order in which listeners are called,

test/parallel/test-event-emitter-remove-listeners.js

+23
Original file line numberDiff line numberDiff line change
@@ -83,3 +83,26 @@ e5.once('removeListener', common.mustCall(function(name, cb) {
8383
}));
8484
e5.removeListener('hello', listener1);
8585
assert.deepEqual([], e5.listeners('hello'));
86+
87+
// a listener removed from an event from within the emit cycle of
88+
// that event* will still be called in that emit cycle
89+
var e6 = new events.EventEmitter(),
90+
firstCount = 0,
91+
secondCount = 0;
92+
93+
function first() {
94+
firstCount++;
95+
e6.removeListener('e6test', second);
96+
}
97+
98+
function second() {
99+
secondCount++;
100+
}
101+
102+
e6.on('e6test', first);
103+
e6.on('e6test', second);
104+
e6.emit('e6test');
105+
e6.emit('e6test');
106+
e6.emit('e6test');
107+
assert.equal(firstCount, 3);
108+
assert.equal(secondCount, 1);

0 commit comments

Comments
 (0)