class Event {
constructor() {
this.events = {}
}
subscribe(event, handler) {
this.events[event] = this.events[event] || []
this.events[event].push(handler)
return () => this.unSubscribe(event, handler)
}
unSubscribe(event, handler) {
let handlers = this.events[event]
if (handlers && Array.isArray(handlers)) {
for (let i = 0; i < handlers.length; i++) {
if (handlers[i] === handler) {
handlers.splice(i, 1)
break
}
}
}
}
emit(event, ...args) {
;(this.events[event] || []).forEach((handler) => {
handler(...args)
})
}
}