由于需要將事件和監(jiān)聽函數(shù)映射起來茫虽,考慮使用對象存儲兩者的對應(yīng)關(guān)系。
簡單代碼邏輯如下:
class EventBus {
static pinstance;
listener = {};
on(event, fn) {
if (this.listener[event]) {
this.listener[event].push(fn);
} else {
this.listener[event] = [fn];
}
}
off(event, fn) {
if (this.listener[event]) {
const index = this.listener[event].find(item => item === fn);
this.listener[event].splice(index, 1);
}
}
emit(event, params) {
if (this.listener[event]) {
this.listener[event].forEach(item => {
item(params);
})
}
}
static get instance() {
if (!this.pinstance) {
this.pinstance = new EventBus();
}
return this.pinstance;
}
}
export default EventBus
使用的時候利用類的單例模式特性
EventBus.instance.on....
EventBus.instance.off...
EventBus.instance.emit....