Skip to main content

发布订阅模式

class EventHub {
constructor() {
// 存放event和map,map为对象,每个key为数组
this.map = {};
}
on(event, fn) {
this.map[event] = this.map[event] || [];
// 注意第一个创建event时的初始函数
this.map[event].push(fn);
}
emit(event, data) {
const fnList = this.map[event] || [];
// 遍历该event的缓存列表,依次执行fn
fnList.forEach((fn) => fn.call(undefined, data));
}
off(event, fn) {
const fnList = this.map[event] || [];
const index = fnList.indexOf(fn);
if (index < 0) return;
fnList.splice(index, 1);
}
once(event, callback) {
// data暂时没东西传进去,但是用了 emit就可以被使用
// 箭头函数
const f = (data) => {
callback(data);
this.off(event, f);
};
this.on(event, f);
}
}