A Hugo incarnation of the blog. https://danilafe.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

27 lines
918 B

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);