initial async processes implementation - not finished

This commit is contained in:
2026-08-16 15:30:04 +02:00
parent a7798436d2
commit c39bbae091
5 changed files with 75 additions and 0 deletions
+50
View File
@@ -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);
}
}
}
}