blog-static/code/typescript-emitter/js1.js

24 lines
544 B
JavaScript

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