Skip to content

Commit

Permalink
doc: update removeListener behaviour
Browse files Browse the repository at this point in the history
This commit updates events doc to describe removeListener behaviour
when it is called within a listener. An example is added to make
it more evident.

A test is also incuded to make this behaviour consistent in future
releases.
fixes nodejs#4759
  • Loading branch information
vaibhav93 committed Feb 12, 2016
1 parent 72c5458 commit 7b91ac0
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
36 changes: 36 additions & 0 deletions doc/api/events.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,42 @@ 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.

Note that once an event has been emitted, all listeners attached to it at the
time of emitting will be called in order. This implies that any `removeListener`
call *after* emitting and *before* the last listener finishes execution will
not affect the current listener array. Subsequent events will behave as expected.

```js
const myEmitter = new MyEmitter();

var callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};

var callbackB = () => {
console.log('B');
};

myEmitter.on('event', callbackA);

myEmitter.on('event', callbackB);

// callbackA removes listener callbackB but it will still be called.
// Interal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// B
// A

// callbackB is now removed.
// Interal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A

```

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
26 changes: 26 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,29 @@ e5.once('removeListener', common.mustCall(function(name, cb) {
}));
e5.removeListener('hello', listener1);
assert.deepEqual([], e5.listeners('hello'));

var e6 = new events.EventEmitter();
count = 0;

function listener3() {
count++;
e6.removeListener('hello', listener4);
}

function listener4() {
count++;
}

e6.on('hello', listener3);
e6.on('hello', listener4);

//listener4 will still be called although it is removed by listener 3.
e6.emit('hello');
//This is so because the interal listener array at time of emit
//was [listener3,listener4]
assert.equal(count, 2);

count = 0;
//Interal listener array [listener3]
e6.emit('hello');
assert.equal(count, 1);

0 comments on commit 7b91ac0

Please sign in to comment.