Skip to content

Commit

Permalink
Add event dispatcher class.
Browse files Browse the repository at this point in the history
  • Loading branch information
i-zolotarenko committed Nov 13, 2023
1 parent f7225e6 commit 7408c87
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions packages/p2p-media-loader-core/src/event-dispatcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
export class EventDispatcher<
T extends { [key: string]: (...args: any) => any },
K extends keyof T = keyof T
> {
private readonly listeners = new Map<keyof T, Set<T[K]>>();

subscribe(eventType: K, listener: T[K]) {
let eventListeners = this.listeners.get(eventType);
if (!eventListeners) {
eventListeners = new Set();
this.listeners.set(eventType, eventListeners);
}
eventListeners.add(listener);
}

unsubscribe(eventType: K, listener: T[K]) {
const eventListeners = this.listeners.get(eventType);
if (!eventListeners) return;
eventListeners.delete(listener);
if (!eventListeners.size) this.listeners.delete(eventType);
}

dispatch(eventType: K, ...args: Parameters<T[K]>) {
const eventListeners = this.listeners.get(eventType);
if (!eventListeners) return;
for (const listener of eventListeners) {
listener(args);
}
}
}

0 comments on commit 7408c87

Please sign in to comment.