class EventBus {
constructor () {
this.event = {}
}
on (type, listener, ...agrs) {
this.event[type] = this.event[type] || []
listener.agrs = [...agrs] // 将参数放到监听函数的属性中
this.event[type].push(listener)
return this.off.bind(listener) // 同步绑定off函数
}
off (type, listener) {
this.event[type] = this.event[type].filter((type) => type !== listener) // 解绑函数
}
fire(type, ...args) {
if (this.event[type]) {
this.event[type].forEach((listener) => {
let allArgs = [...agrs, ...listener.agrs]
listener.call(this, ...allArgs)
})
}
}
once (type, listener) {
this.events[type] = this.events[type] || [];
function proxyFun(...agrs) {
listener.call(this, ...agrs)
this.off(type, listener)
}
this.event[type].push(proxyFun)
}
}