diff --git a/src/event-mixin.spec.ts b/src/event-mixin.spec.ts index 36a4e60..454ef5c 100644 --- a/src/event-mixin.spec.ts +++ b/src/event-mixin.spec.ts @@ -42,6 +42,22 @@ describe('a class with events', () => { expect(handlerTwoArgs).toHaveLength(1); expect(handlerTwoArgs[0]).toBe(42); }); + + it('should remove all handlers when removeAllListeners is called', () => { + expect.hasAssertions(); + const handlerOneArgs: number[] = []; + const handler = (value: number) => { + handlerOneArgs.push(value); + }; + myClass.on('eventOne', handler); + myClass.fireEventOne(); + expect(handlerOneArgs).toHaveLength(1); + expect(handlerOneArgs[0]).toBe(42); + + myClass.removeAllListeners(); + myClass.fireEventOne(); + expect(handlerOneArgs).toHaveLength(1); // Should still be 1, as all listeners should be removed + }); }); interface ChildEvents { @@ -75,4 +91,22 @@ describe('a child class', () => { expect(eventOneArgs).toHaveLength(1); expect(eventThreeArgs).toHaveLength(1); }); + + it('should remove all handlers from parent and child when removeAllListeners is called', () => { + expect.hasAssertions(); + + const eventOneArgs: number[] = []; + const eventThreeArgs: string[] = []; + + myClass.on('eventOne', (value: number) => eventOneArgs.push(value)); + myClass.on('eventThree', (value: string) => eventThreeArgs.push(value)); + + myClass.removeAllListeners(); + + myClass.fireEventOne(); + myClass.fireEventThree(); + + 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 + }); }); diff --git a/src/event-mixin.ts b/src/event-mixin.ts index b3b0a72..324a044 100644 --- a/src/event-mixin.ts +++ b/src/event-mixin.ts @@ -63,6 +63,18 @@ export function AddEvents(Base: TBase) { off>(eventName: K, handler: E) { (this as any)[eventName].off(handler); } + + /** + * 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(); + } + }); + } }; } diff --git a/src/typed-event.ts b/src/typed-event.ts index 3189c6d..eb2155d 100644 --- a/src/typed-event.ts +++ b/src/typed-event.ts @@ -57,4 +57,11 @@ export class TypedEvent { emit(...args: Parameters): void { this.emitter.emit('event', ...args); } + + /** + * Remove all listeners from this event. + */ + removeAllListeners(): void { + this.emitter.removeAllListeners('event'); + } }