1
0
Fork 0
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:
blairzhao111 2020-06-09 21:07:25 +08:00 committed by GitHub
parent 878f306a39
commit 6c21ba0575
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 7 deletions

View file

@ -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();

View file

@ -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() {