class EventBus {
constructor() {
this._event = new Map()
}
on (type, fn) {
let handler = this._event.get(type)
if(!handler) {
this._event.set(type, [fn])
} else {
handler.push(fn)
}
}
emit (type, ...args) {
let handler = this._event.get(type)
handler.forEach((fn) => {
fn.apply(this, args)
})
}
off (type, fn) {
let handler = this._event.get(type)
handler.splice(handler.findIndex(e => e === fn), 1)
}
once (type, fn) {
let _self = this
function handler () {
_self.off(type, fn)
fn.apply(null, arguments)
}
this.on(type, handler)
}
}