Skip to content

Commit

Permalink
fix: ensure methods are checked on the prototype chain
Browse files Browse the repository at this point in the history
  • Loading branch information
andiwils committed Jun 10, 2024
1 parent fa0672e commit 5d7a206
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
13 changes: 13 additions & 0 deletions src/event-mixin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,17 @@ describe('a child class', () => {
expect(eventOneArgs).toHaveLength(0); // Should be 0, as all listeners should be removed
expect(eventThreeArgs).toHaveLength(0); // Should be 0, as all listeners should be removed
});

it('should remove all handlers from inherited classes when removeAllListeners is called', () => {
expect.hasAssertions();

const eventTwoArgs: boolean[] = [];
myClass.on('eventTwo', (value: boolean) => eventTwoArgs.push(value));

myClass.removeAllListeners();

myClass.fireEventTwo();

expect(eventTwoArgs).toHaveLength(0); // Should be 0, as all listeners should be removed
});
});
23 changes: 18 additions & 5 deletions src/event-mixin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,25 @@ export function AddEvents<TBase extends Constructor, U>(Base: TBase) {
* Remove all event listeners from all events.
*/
removeAllListeners() {
Object.keys(this).forEach((eventName) => {
const event = (this as any)[eventName];
if (event instanceof TypedEvent) {
event.removeAllListeners();
/**
* Recursively remove all listeners from the given object and its prototype chain. This is
* necessary because the events may be defined on the prototype chain.
*
* @param obj - The object to remove listeners from.
*/
function removeListeners(obj: any) {
if (!obj || obj === Object.prototype) {
return;
}
});
Object.keys(obj).forEach((eventName) => {
const event = obj[eventName];
if (event instanceof TypedEvent) {
event.removeAllListeners();
}
});
removeListeners(Object.getPrototypeOf(obj));
}
removeListeners(this);
}
};
}
Expand Down

0 comments on commit 5d7a206

Please sign in to comment.