elexis/lib/$EventManager.ts

32 lines
1.2 KiB
TypeScript
Raw Permalink Normal View History

export class $EventManager<EM extends $EventMap> {
private eventMap = new Map<string, Set<Function>>();
2024-02-01 23:47:13 +08:00
//@ts-expect-error
fire<K extends keyof EM>(type: K, ...args: EM[K]) {
this.eventMap.get(type as string)?.forEach(fn => fn(...args as []));
2024-02-01 23:47:13 +08:00
return this
}
//@ts-expect-error
on<K extends keyof EM>(type: K, callback: (...args: EM[K]) => any) {
const set = this.eventMap.get(type as string) ?? this.eventMap.set(type as string, new Set()).get(type as string);
set?.add(callback);
2024-02-01 23:47:13 +08:00
return this
}
//@ts-expect-error
off<K extends keyof EM>(type: K, callback: (...args: EM[K]) => any) {
this.eventMap.get(type as string)?.delete(callback);
2024-02-01 23:47:13 +08:00
return this
}
//@ts-expect-error
once<K extends keyof EM>(type: K, callback: (...args: EM[K]) => any) {
const onceFn = (...args: []) => {
this.eventMap.get(type as string)?.delete(onceFn);
2024-02-01 23:47:13 +08:00
//@ts-expect-error
callback(...args);
}
const set = this.eventMap.get(type as string) ?? this.eventMap.set(type as string, new Set()).get(type as string)
set?.add(onceFn);
2024-02-01 23:47:13 +08:00
return this;
}
}
export interface $EventMap {}