手写实现自定义事件总线
class FhEventBus {
constructor() {
this.eventBus = {}
}
// 监听
on(eventName, eventCallback, thisArg) {
let handlers = this.eventBus[eventName]
if(!handlers) {
handlers = []
this.eventBus[eventName] = handlers
}
handlers.push({
eventCallback,
thisArg
})
}
// 取消监听
off(eventName, eventCallback) {
const handlers = this.eventBus[eventName]
if(!handlers) return
handlers.forEach(item => {
if(item.eventCallback === eventCallback){
const index = handlers.indexOf(item)
if(!index) return
handlers.splice(index, 1)
}
})
}
// 发射事件
emit(eventName, ...payload) {
const handlers = this.eventBus[eventName]
if(!handlers) {
return
}
for (const item of handlers) {
const { eventCallback, thisArg } = item
eventCallback.apply(thisArg, payload)
}
}
}
const eventBus = new FhEventBus()
// main.js
eventBus.on('abc', function() {
console.log('监听abc1', this);
}, {name: 'Fhup'})
const handlerCallback = function() {
console.log('监听abc2', this);
}
eventBus.on('abc', handlerCallback, {name: 'xxx'})
// utils.js
eventBus.emit('abc', 123)
eventBus.off('abc', handlerCallback)
console.log('---------');
eventBus.emit('abc', 123)
这个比较好理解.就不写注释了