Skip to content

Commit

Permalink
[major] Ignore listeners not added with WebSocket#addEventListener()
Browse files Browse the repository at this point in the history
Make `WebSocket.prototype.removeEventListener()` only remove listeners
added with `WebSocket.prototype.addEventListener()` and only one at
time.
  • Loading branch information
lpinca committed Jul 29, 2021
1 parent 9558ed1 commit ea95d9c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
4 changes: 3 additions & 1 deletion doc/ws.md
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,9 @@ The current state of the connection. This is one of the ready state constants.
- `type` {String} A string representing the event type to remove.
- `listener` {Function} The listener to remove.

Removes an event listener emulating the `EventTarget` interface.
Removes an event listener emulating the `EventTarget` interface. This method
only removes listeners added with
[`websocket.addEventListener()`](#websocketaddeventlistenertype-listener-options).

### websocket.send(data[, options][, callback])

Expand Down
3 changes: 2 additions & 1 deletion lib/event-target.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,9 @@ const EventTarget = {
*/
removeEventListener(type, handler) {
for (const listener of this.listeners(type)) {
if (listener === handler || listener[kListener] === handler) {
if (listener[kListener] === handler) {
this.removeListener(type, listener);
break;
}
}
}
Expand Down
24 changes: 24 additions & 0 deletions test/websocket.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2233,6 +2233,30 @@ describe('WebSocket', () => {

assert.strictEqual(ws.listenerCount('message'), 0);
assert.strictEqual(ws.listenerCount('open'), 0);

// Multiple listeners.
ws.addEventListener('message', NOOP);
ws.addEventListener('message', NOOP);

assert.strictEqual(ws.listeners('message')[0][kListener], NOOP);
assert.strictEqual(ws.listeners('message')[1][kListener], NOOP);

ws.removeEventListener('message', NOOP);

assert.strictEqual(ws.listeners('message')[0][kListener], NOOP);

ws.removeEventListener('message', NOOP);

assert.strictEqual(ws.listenerCount('message'), 0);

// Listeners not added with `websocket.addEventListener()`.
ws.on('message', NOOP);

assert.deepStrictEqual(ws.listeners('message'), [NOOP]);

ws.removeEventListener('message', NOOP);

assert.deepStrictEqual(ws.listeners('message'), [NOOP]);
});

it('wraps text data in a `MessageEvent`', (done) => {
Expand Down

0 comments on commit ea95d9c

Please sign in to comment.