上班期间因为业务需要写了一个简单的eventBus方法供自己使用,采用单例模式来实现相关的功能。
class EventBus {
constructor() {
this.events = {};
}
static get instance() {
if (!this._instance) {
this._instance = new EventBus();
}
return this._instance;
}
emit(type, params) {
if (!this.events[type]) {
return;
}
this.events[type].forEach((item) => {
item.fun.call(this, params);
if (item.isOnce) {
this.removeEventListener(type, item.fun);
}
});
}
addEventListener(type, fun, isOnce = false) {
if (!this.events[type]) {
this.events[type] = [];
}
this.events[type].push({ fun, isOnce });
}
removeEventListener(type, fun) {
if (!this.events[type]) {
return;
}
const index = this.events[type].findIndex((item) => item.fun === fun);
this.events[type].splice(index, 1);
}
once(type, fun) {
this.addEventListener(type, fun, true);
}
}
export default EventBus;
使用方法:
import EventBus from "@/utils/eventBus";
const eventBus = EventBus.instance;