blog-static/code/typescript-emitter/ts.ts

28 lines
918 B
TypeScript
Raw Normal View History

class EventEmitter<T> {
private handlers: { [eventName in keyof T]?: ((value: T[eventName]) => void)[] }
constructor() {
this.handlers = {}
}
emit<K extends keyof T>(event: K, value: T[K]): void {
this.handlers[event]?.forEach(h => h(value));
}
addHandler<K extends keyof T>(event: K, handler: (value: T[K]) => void): void {
if(!this.handlers[event]) {
this.handlers[event] = [handler];
} else {
this.handlers[event].push(handler);
}
}
}
const emitter = new EventEmitter<{ numberChange: number, stringChange: string }>();
emitter.addHandler("numberChange", n => console.log("New number value is: ", n));
emitter.addHandler("stringChange", s => console.log("New string value is: ", s));
emitter.emit("numberChange", 1);
emitter.emit("stringChange", "3");
emitter.emit("numberChange", "1");
emitter.emit("stringChange", 3);