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

24 lines
628 B
JavaScript

class EventEmitter {
constructor() {
this.handlers = {}
}
emit(event, value) {
this.handlers[event]?.forEach(h => h(value));
}
addHandler(event, handler) {
if(!this.handlers[event]) {
this.handlers[event] = [handler];
} else {
this.handlers[event].push(handler);
}
}
}
const emitter = new EventEmitter();
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");