mirror of
https://github.com/sussy-code/smov.git
synced 2025-01-01 16:37:39 +01:00
make emitter
This commit is contained in:
parent
a4df114fc5
commit
8fe3385fb1
1 changed files with 33 additions and 0 deletions
33
src/utils/events.ts
Normal file
33
src/utils/events.ts
Normal file
|
@ -0,0 +1,33 @@
|
||||||
|
export type EventMap = Record<string, any>;
|
||||||
|
type EventKey<T extends EventMap> = string & keyof T;
|
||||||
|
type EventReceiver<T> = (params: T) => void;
|
||||||
|
|
||||||
|
export interface Emitter<T extends EventMap> {
|
||||||
|
on<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void;
|
||||||
|
off<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void;
|
||||||
|
emit<K extends EventKey<T>>(eventName: K, params: T[K]): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Listener<T extends EventMap> {
|
||||||
|
on<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function makeEmitter<T extends EventMap>(): Emitter<T> {
|
||||||
|
const listeners: Partial<
|
||||||
|
Record<EventKey<T>, ((...params: any[]) => void)[]>
|
||||||
|
> = {};
|
||||||
|
|
||||||
|
return {
|
||||||
|
on(eventName, fn) {
|
||||||
|
if (!listeners[eventName]) listeners[eventName] = [];
|
||||||
|
listeners[eventName]?.push(fn);
|
||||||
|
},
|
||||||
|
off(eventName, fn) {
|
||||||
|
listeners[eventName] =
|
||||||
|
listeners[eventName]?.filter((v) => v !== fn) ?? [];
|
||||||
|
},
|
||||||
|
emit(eventName, params) {
|
||||||
|
(listeners[eventName] ?? []).forEach((fn) => fn(params));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
Loading…
Reference in a new issue