Skip to content

Instantly share code, notes, and snippets.

@melbourne2991
Created May 10, 2022 05:37
Show Gist options
  • Save melbourne2991/5d3c41d9a6353dcacfe984d65b7a9f9c to your computer and use it in GitHub Desktop.
Save melbourne2991/5d3c41d9a6353dcacfe984d65b7a9f9c to your computer and use it in GitHub Desktop.
Typed event emitter
export type IEventListener<P> = (payload: P) => void;
export class Events<T1 extends Record<string, any>> {
private listeners: Map<string, IEventListener<any>[]> = new Map();
readonly addListener = <T2 extends keyof T1>(
eventType: T2,
listener: IEventListener<T1[T2]>
) => {
let arr = this.listeners.get(eventType as string);
if (!Array.isArray(arr)) {
arr = [];
this.listeners.set(eventType as string, arr);
}
arr.push(listener);
};
readonly removeListener = <T2 extends keyof T1>(
eventType: T2,
listener: IEventListener<T1[T2]>
) => {
let arr = this.listeners.get(eventType as string);
if (arr) {
const idx = arr.indexOf(listener);
arr.splice(idx, 1);
}
}
readonly emit = <T2 extends keyof T1>(eventType: T2, payload: T1[T2]) => {
const arr = this.listeners.get(eventType as any);
if (arr && arr.length) {
for (const listener of arr) {
listener(payload);
}
}
return this;
};
readonly on = this.addListener
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment