Skip to content

Commit

Permalink
adding in listenerCount
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredwray committed Oct 15, 2024
1 parent 6a222dc commit 6b17b31
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/eventified.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -130,4 +134,13 @@ export class Eventified implements IEventEmitter {
}
}
}

public getAllListeners(): EventListener[] {
let result = new Array<EventListener>();
for (const listeners of this._eventListeners.values()) {
result = result.concat(listeners);
}

return result;
}
}
13 changes: 13 additions & 0 deletions test/eventified.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});

0 comments on commit 6b17b31

Please sign in to comment.