Skip to content

Commit

Permalink
doc: emitter.removeListener clarification
Browse files Browse the repository at this point in the history
Fix based on nodejs#4764 by
@drjokepu.

Fixes: nodejs#4759
  • Loading branch information
dirceu committed Feb 12, 2016
1 parent 773b901 commit 9e33450
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
26 changes: 26 additions & 0 deletions doc/api/events.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,32 @@ listener array. If any single listener has been added multiple times to the
listener array for the specified `event`, then `removeListener` must be called
multiple times to remove each instance.

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:

```js
const EventEmitter = require('events');
const emitter = new EventEmitter();

function first() {
console.log('first! this will always be called.');
emitter.removeListener('test', second);
}

function second() {
console.log('second! this will only be called once in this context.');
}

emitter.on('test', first);
emitter.on('test', second);

emitter.emit('test');
// first! this will always be called.
// second! this will only be called once in this context.

emitter.emit('test');
// first! this will always be called.
```

Because listeners are managed using an internal array, calling this will
change the position indices of any listener registered *after* the listener
being removed. This will not impact the order in which listeners are called,
Expand Down
23 changes: 23 additions & 0 deletions test/parallel/test-event-emitter-remove-listeners.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,26 @@ e5.once('removeListener', common.mustCall(function(name, cb) {
}));
e5.removeListener('hello', listener1);
assert.deepEqual([], e5.listeners('hello'));

// a listener removed from an event from within the emit cycle of
// that event* will still be called in that emit cycle
var e6 = new events.EventEmitter(),
firstCount = 0,
secondCount = 0;

function first() {
firstCount++;
e6.removeListener('e6test', second);
}

function second() {
secondCount++;
}

e6.on('e6test', first);
e6.on('e6test', second);
e6.emit('e6test');
e6.emit('e6test');
e6.emit('e6test');
assert.equal(firstCount, 3);
assert.equal(secondCount, 1);

0 comments on commit 9e33450

Please sign in to comment.