Added typed emitter
This commit is contained in:
parent
ffaf8558b2
commit
e4c7dea9a5
@ -1,28 +1,33 @@
|
|||||||
export type Listener<T> = (event: T) => any;
|
export type Listener = (...args: any[]) => any;
|
||||||
|
export type TypedEvents = {[k in string | symbol]: Listener} & {'*': (event: string, ...args: any[]) => any};
|
||||||
|
|
||||||
export class Emitter<T> {
|
export class TypedEmitter<T extends TypedEvents = TypedEvents> {
|
||||||
private listeners: {[key: string]: Listener<T>} = {};
|
private listeners: { [key in keyof T]?: Function[] } = {};
|
||||||
|
|
||||||
constructor() { }
|
emit<K extends keyof T>(event: K, ...args: Parameters<T[K]>) {
|
||||||
|
(this.listeners['*'] || []).forEach(l => l(event, ...args));
|
||||||
|
(this.listeners[event] || []).forEach(l => l(...args));
|
||||||
|
};
|
||||||
|
|
||||||
emit(e: T) {
|
off<K extends keyof T = string>(event: K, listener: T[K]): this {
|
||||||
Object.values(this.listeners).forEach(l => l(e));
|
console.log('cleared');
|
||||||
|
this.listeners[event] = (this.listeners[event] || []).filter(l => l === listener);
|
||||||
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
listen(fn: Listener<T>): () => {};
|
on<K extends keyof T = string>(event: K, listener: T[K]) {
|
||||||
listen(key: string, fn: Listener<T>): () => {};
|
if(!this.listeners[event]) this.listeners[event] = [];
|
||||||
listen(keyOrFn: string | Listener<T>, fn?: Listener<T>): () => {} {
|
this.listeners[event]?.push(listener);
|
||||||
const func: any = fn ? fn : keyOrFn;
|
return () => this.off(event, listener);
|
||||||
const key: string = typeof keyOrFn == 'string' ? keyOrFn :
|
|
||||||
`_${Object.keys(this.listeners).length.toString()}`;
|
|
||||||
this.listeners[<any>key] = func;
|
|
||||||
return () => delete this.listeners[<any>key];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
once(fn: Listener<T>) {
|
once<K extends keyof T = string>(event: K, listener?: T[K]): Promise<any> {
|
||||||
const stop = this.listen(e => {
|
return new Promise(res => {
|
||||||
fn(e);
|
const unsubscribe = this.on(event, <any>((...args: any) => {
|
||||||
stop();
|
res(args.length == 1 ? args[0] : args);
|
||||||
|
if(listener) listener(...args);
|
||||||
|
unsubscribe();
|
||||||
|
}));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user