Skip to content

Commit ea95d9c

Browse files
committedJul 29, 2021
[major] Ignore listeners not added with WebSocket#addEventListener()
Make `WebSocket.prototype.removeEventListener()` only remove listeners added with `WebSocket.prototype.addEventListener()` and only one at time.
1 parent 9558ed1 commit ea95d9c

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed
 

‎doc/ws.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,9 @@ The current state of the connection. This is one of the ready state constants.
476476
- `type` {String} A string representing the event type to remove.
477477
- `listener` {Function} The listener to remove.
478478

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

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

‎lib/event-target.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -173,8 +173,9 @@ const EventTarget = {
173173
*/
174174
removeEventListener(type, handler) {
175175
for (const listener of this.listeners(type)) {
176-
if (listener === handler || listener[kListener] === handler) {
176+
if (listener[kListener] === handler) {
177177
this.removeListener(type, listener);
178+
break;
178179
}
179180
}
180181
}

‎test/websocket.test.js

+24
Original file line numberDiff line numberDiff line change
@@ -2233,6 +2233,30 @@ describe('WebSocket', () => {
22332233

22342234
assert.strictEqual(ws.listenerCount('message'), 0);
22352235
assert.strictEqual(ws.listenerCount('open'), 0);
2236+
2237+
// Multiple listeners.
2238+
ws.addEventListener('message', NOOP);
2239+
ws.addEventListener('message', NOOP);
2240+
2241+
assert.strictEqual(ws.listeners('message')[0][kListener], NOOP);
2242+
assert.strictEqual(ws.listeners('message')[1][kListener], NOOP);
2243+
2244+
ws.removeEventListener('message', NOOP);
2245+
2246+
assert.strictEqual(ws.listeners('message')[0][kListener], NOOP);
2247+
2248+
ws.removeEventListener('message', NOOP);
2249+
2250+
assert.strictEqual(ws.listenerCount('message'), 0);
2251+
2252+
// Listeners not added with `websocket.addEventListener()`.
2253+
ws.on('message', NOOP);
2254+
2255+
assert.deepStrictEqual(ws.listeners('message'), [NOOP]);
2256+
2257+
ws.removeEventListener('message', NOOP);
2258+
2259+
assert.deepStrictEqual(ws.listeners('message'), [NOOP]);
22362260
});
22372261

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

0 commit comments

Comments
 (0)
Please sign in to comment.