mirror of
https://github.com/denoland/deno.git
synced 2024-11-21 15:04:11 -05:00
fix(std/node): emitter.removeAllListeners (#5583)
When given a non-registered eventName to emitter.removeAllListeners(eventName), current code would remove all listeners instead of silently skip, which is not ideal.
This commit is contained in:
parent
878f306a39
commit
6c21ba0575
2 changed files with 28 additions and 7 deletions
|
@ -279,13 +279,15 @@ export default class EventEmitter {
|
|||
return this;
|
||||
}
|
||||
|
||||
if (eventName && this._events.has(eventName)) {
|
||||
const listeners = (this._events.get(eventName) as Array<
|
||||
Function | WrappedFunction
|
||||
>).slice(); // Create a copy; We use it AFTER it's deleted.
|
||||
this._events.delete(eventName);
|
||||
for (const listener of listeners) {
|
||||
this.emit("removeListener", eventName, listener);
|
||||
if (eventName) {
|
||||
if (this._events.has(eventName)) {
|
||||
const listeners = (this._events.get(eventName) as Array<
|
||||
Function | WrappedFunction
|
||||
>).slice(); // Create a copy; We use it AFTER it's deleted.
|
||||
this._events.delete(eventName);
|
||||
for (const listener of listeners) {
|
||||
this.emit("removeListener", eventName, listener);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const eventList: [string | symbol] = this.eventNames();
|
||||
|
|
|
@ -245,6 +245,25 @@ test({
|
|||
},
|
||||
});
|
||||
|
||||
test({
|
||||
name: "Provide a non-existent event to removeAllListeners will do nothing",
|
||||
fn() {
|
||||
const testEmitter = new EventEmitter();
|
||||
testEmitter.on("event", shouldNeverBeEmitted);
|
||||
testEmitter.on("event", shouldNeverBeEmitted);
|
||||
testEmitter.on("other event", shouldNeverBeEmitted);
|
||||
testEmitter.on("other event", shouldNeverBeEmitted);
|
||||
testEmitter.once("other event", shouldNeverBeEmitted);
|
||||
assertEquals(testEmitter.listenerCount("event"), 2);
|
||||
assertEquals(testEmitter.listenerCount("other event"), 3);
|
||||
|
||||
testEmitter.removeAllListeners("non-existent");
|
||||
|
||||
assertEquals(testEmitter.listenerCount("event"), 2);
|
||||
assertEquals(testEmitter.listenerCount("other event"), 3);
|
||||
},
|
||||
});
|
||||
|
||||
test({
|
||||
name: "Remove individual listeners, which can also be chained",
|
||||
fn() {
|
||||
|
|
Loading…
Reference in a new issue