initial async processes implementation - not finished
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
export class EventEmitter<TEvents> {
|
||||
private handlers: Map<keyof TEvents, Set<Function>> = new Map();
|
||||
|
||||
public on<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
|
||||
const listeners = this.handlers.get(type);
|
||||
|
||||
if (listeners) {
|
||||
listeners.add(handler);
|
||||
} else {
|
||||
const set: Set<Function> = new Set();
|
||||
set.add(handler);
|
||||
this.handlers.set(type, set);
|
||||
}
|
||||
|
||||
return (): void => this.off(type, handler);
|
||||
}
|
||||
|
||||
public off<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): void {
|
||||
this.handlers.get(type)?.delete(handler);
|
||||
}
|
||||
|
||||
public once<K extends keyof TEvents>(type: K, handler: (payload: TEvents[K]) => void): () => void {
|
||||
const listeners = this.handlers.get(type);
|
||||
|
||||
const wrapper = (payload: TEvents[K]) => {
|
||||
handler(payload);
|
||||
this.off(type, wrapper);
|
||||
};
|
||||
|
||||
if (listeners) {
|
||||
listeners.add(wrapper);
|
||||
} else {
|
||||
const set: Set<Function> = new Set();
|
||||
set.add(wrapper);
|
||||
this.handlers.set(type, set);
|
||||
}
|
||||
|
||||
return (): void => this.off(type, wrapper);
|
||||
}
|
||||
|
||||
public emit<K extends keyof TEvents>(type: K, payload: TEvents[K]): void {
|
||||
const listeners = this.handlers.get(type);
|
||||
|
||||
if (listeners) {
|
||||
for (const listener of [...listeners]) {
|
||||
listener(payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user