以下是EventHub的简单实现
class EventHub {
constructor() {
this.events = {}
}
on(eventName, fn) {
if(!this.events[eventName]) {
this.events[eventName] = []
}
this.events[eventName].push(fn)
}
emit(eventName, params) {
let fnLists = this.events[eventName]
if(Array.isArray(fnLists) && fnLists.length > 0) {
fnLists.map(fnList => {
fnList.apply(this, params)
})
}
}
off(eventName, fn) {
let fnLists = this.events[eventName]
for(let i=0, len=fnLists; i < len; i++) {
if(fnLists[i] === fn) {
delete fnLists[i]
break;
}
}
}
}
来源:CSDN
作者:卡卡的笔录
链接:https://blog.csdn.net/m0_38102188/article/details/103927214