elexis/lib/$EventManager.ts
defaultkavy 4c078c26b6
v0.3.0
- remove: class $EventMethod, $Event.
- change: $EventManager rewrite logic.
- change: most $Node base node element generic type have new EM(EventMap) parameter.
- new: $EventTarget.
- change: $Node extends $EventTarget.
- change: mix dom events and $EventManager events into $EventTarget.on().off().once().
- fix: $Container.insert() process synchronous when passing an not async function
- new: $Window element.
- fix: $(document.documentElement) throw error.
- new: $KeyboardManager, $FocusManager, $PointerManager.
- new: $ global methods:
  - $.events() return new $EventManager.
  - $.pointers() return new $PointerManager.
  - $.keys() return new $KeyboardManager.
  - $.focus() return new $FocusManager.
  - $.call()
- change: $Media extends $HTMLElement
- change: $Anchor.href() support $State parameter.
- new: $State.convert()
2024-10-17 11:54:28 +08:00

32 lines
1.2 KiB
TypeScript

export class $EventManager<EM extends $EventMap> {
private eventMap = new Map<string, Set<Function>>();
//@ts-expect-error
fire<K extends keyof EM>(type: K, ...args: EM[K]) {
this.eventMap.get(type as string)?.forEach(fn => fn(...args as []));
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);
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);
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);
//@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);
return this;
}
}
export interface $EventMap {}