class LQEventBus {
constructor() {
this.eventBus = {}
};
on(eventName,callBack,thisArg) {
let handers = this.eventBus[eventName]
if(!handers) {
handers = []
this.eventBus[eventName] = handers
}
handers.push({
callBack,
thisArg
})
};
emit(eventName,payLoad) {
let handers = this.eventBus[eventName]
handers.forEach(hander => {
hander.callBack.apply(hander.thisArg,payLoad)
});
};
off(eventName,callBack) {
let handers = this.eventBus[eventName]
if(!handers) return
const newHanders = [...handers]
for(let i = 0;i <newHanders.length;i++) {
if(callBack == newHanders[i].callBack) {
const index = handers.indexOf(newHanders[i])
if(index !== -1) {
handers.splice(index,1)
}
}
}
}
}
// 测试代码
const eventBus = new LQEventBus()
function bar() {
console.log('bar')
}
eventBus.on('abc',function() {
console.log("abc1")
})
eventBus.on('abc2',function() {
console.log("abc2")
})
eventBus.on('abc',bar)
eventBus.off('abc',bar)
eventBus.emit('abc')
eventBus.emit('abc2')