Add draft of TypeScript typesafe event emitter post

This commit is contained in:
2021-09-04 18:32:08 -07:00
parent d5f478b3c6
commit 3c905aa1d7
4 changed files with 193 additions and 0 deletions

View File

@@ -0,0 +1,23 @@
class EventEmitter {
constructor() {
this.handlers = {}
}
emit(event) {
this.handlers[event]?.forEach(h => h());
}
addHandler(event, handler) {
if(!this.handlers[event]) {
this.handlers[event] = [handler];
} else {
this.handlers[event].push(handler);
}
}
}
const emitter = new EventEmitter();
emitter.addHandler("start", () => console.log("Started!"));
emitter.addHandler("end", () => console.log("Ended!"));
emitter.emit("end");
emitter.emit("start");