From 93e6b3f74dab6ccc68b3117cbae1009ce91a4859 Mon Sep 17 00:00:00 2001 From: Robert Nagy Date: Mon, 9 Sep 2019 13:33:51 +0200 Subject: [PATCH 1/7] events: add/removeListener should call on/off Previously these used alias which caused surprising behaviour when trying to override add/removeListener, e.g. Readable. This resolves this by making add/remove actually call the corresponding function through the prototype chain. --- doc/api/events.md | 61 ++++++++++++++------------- lib/events.js | 8 +++- test/parallel/test-events-override.js | 17 ++++++++ 3 files changed, 55 insertions(+), 31 deletions(-) create mode 100644 test/parallel/test-events-override.js diff --git a/doc/api/events.md b/doc/api/events.md index 021c6b05989dad..07f05aa5ed7c4f 100644 --- a/doc/api/events.md +++ b/doc/api/events.md @@ -290,8 +290,35 @@ added: v0.1.26 --> * `eventName` {string|symbol} * `listener` {Function} +* Returns: {EventEmitter} + +Adds the `listener` function to the end of the listeners array for the +event named `eventName`. No checks are made to see if the `listener` has +already been added. Multiple calls passing the same combination of `eventName` +and `listener` will result in the `listener` being added, and called, multiple +times. + +```js +server.addListener('connection', (stream) => { + console.log('someone connected!'); +}); +``` + +Returns a reference to the `EventEmitter`, so that calls can be chained. -Alias for `emitter.on(eventName, listener)`. +By default, event listeners are invoked in the order they are added. The +`emitter.prependListener()` method can be used as an alternative to add the +event listener to the beginning of the listeners array. + +```js +const myEE = new EventEmitter(); +myEE.addListener('foo', () => console.log('a')); +myEE.prependListener('foo', () => console.log('b')); +myEE.emit('foo'); +// Prints: +// b +// a +``` ### emitter.emit(eventName[, ...args])