From 6b17b3171ccae0902451466e8a1bce20fd4d0334 Mon Sep 17 00:00:00 2001 From: Jared Wray Date: Tue, 15 Oct 2024 12:28:17 -0700 Subject: [PATCH] adding in listenerCount --- src/eventified.ts | 15 ++++++++++++++- test/eventified.test.ts | 13 +++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/eventified.ts b/src/eventified.ts index b526ed3..853f8ae 100644 --- a/src/eventified.ts +++ b/src/eventified.ts @@ -22,7 +22,11 @@ export class Eventified implements IEventEmitter { return this; } - listenerCount(eventName: string | symbol): number { + listenerCount(eventName?: string | symbol): number { + if (!eventName) { + return this.getAllListeners().length; + } + const listeners = this._eventListeners.get(eventName as string); return listeners ? listeners.length : 0; } @@ -130,4 +134,13 @@ export class Eventified implements IEventEmitter { } } } + + public getAllListeners(): EventListener[] { + let result = new Array(); + for (const listeners of this._eventListeners.values()) { + result = result.concat(listeners); + } + + return result; + } } diff --git a/test/eventified.test.ts b/test/eventified.test.ts index a694711..5b24a82 100644 --- a/test/eventified.test.ts +++ b/test/eventified.test.ts @@ -148,4 +148,17 @@ describe('Eventified', () => { t.expect(dataReceived).toBe(1); }); + + test('get listener count', t => { + const emitter = new Eventified(); + const listener = () => {}; + + emitter.on('test-event', listener); + emitter.on('test-event', listener); + emitter.on('test-event1', listener); + emitter.on('test-event2', listener); + + t.expect(emitter.listenerCount()).toBe(4); + t.expect(emitter.listenerCount('test-event')).toBe(2); + }); });