代码挺简单的就不多说了,直接上代码;
class EventHub {
cache = {}
on(eventName, fn) {
cache[eventName] = cache[eventName] || [];
cache[eventName].push(fn);
}
emit(eventName, ...args){
for (let i = 0; i < cache[eventName].length; i++) {
cache[eventName][i].apply(this, args);
}
}
// 如果开发者在 事件函数中调用这个off 那么在emit中的循环必然会乱入
// 所以这里应该要处理下应该要等到遍历结束才能真正执行代码块
off(eventName, fn) {
const index = this.cache[eventName].indexOf(fn);
if (index === -1) { return false;}
this.cache[eventName].splice(index, 1);
}
}