2024-10-17 11:54:28 +08:00
|
|
|
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]) {
|
2024-10-17 11:54:28 +08:00
|
|
|
this.eventMap.get(type as string)?.forEach(fn => fn(...args as []));
|
2024-02-01 23:47:13 +08:00
|
|
|
return this
|
|
|
|
}
|
|
|
|
//@ts-expect-error
|
2024-04-23 18:18:43 +08:00
|
|
|
on<K extends keyof EM>(type: K, callback: (...args: EM[K]) => any) {
|
2024-10-17 11:54:28 +08:00
|
|
|
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
|
2024-04-23 18:18:43 +08:00
|
|
|
off<K extends keyof EM>(type: K, callback: (...args: EM[K]) => any) {
|
2024-10-17 11:54:28 +08:00
|
|
|
this.eventMap.get(type as string)?.delete(callback);
|
2024-02-01 23:47:13 +08:00
|
|
|
return this
|
|
|
|
}
|
|
|
|
//@ts-expect-error
|
2024-04-23 18:18:43 +08:00
|
|
|
once<K extends keyof EM>(type: K, callback: (...args: EM[K]) => any) {
|
2024-10-17 11:54:28 +08:00
|
|
|
const onceFn = (...args: []) => {
|
|
|
|
this.eventMap.get(type as string)?.delete(onceFn);
|
2024-02-01 23:47:13 +08:00
|
|
|
//@ts-expect-error
|
|
|
|
callback(...args);
|
|
|
|
}
|
2024-10-17 11:54:28 +08:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|
2024-10-17 11:54:28 +08:00
|
|
|
|
|
|
|
export interface $EventMap {}
|