Skip to content

Instantly share code, notes, and snippets.

@tranduybau
Created July 23, 2020 03:05
Show Gist options
  • Save tranduybau/2702fb766aa2a6aae4128bd98eca214d to your computer and use it in GitHub Desktop.
Save tranduybau/2702fb766aa2a6aae4128bd98eca214d to your computer and use it in GitHub Desktop.
import Vue from 'vue';
class EventBus {
constructor(vue) {
if (!this.handles) {
Object.defineProperty(this, 'handles', {
value: {},
enumerable: false,
});
}
this.Vue = vue;
this.eventMapUid = {};
}
setEventMapUid(uid, eventName) {
if (!this.eventMapUid[uid]) this.eventMapUid[uid] = [];
this.eventMapUid[uid].push(eventName);
}
$on(eventName, callback, vm) {
if (!this.handles[eventName]) this.handles[eventName] = [];
this.handles[eventName].push(callback);
if (vm instanceof this.Vue) this.setEventMapUid(vm._uid, eventName); // eslint-disable-line
}
$emit() {
const args = [...arguments]; // eslint-disable-line
const eventName = args[0];
const params = args.slice(1);
if (this.handles[eventName]) {
const len = this.handles[eventName].length;
for (let i = 0; i < len; i++) { // eslint-disable-line
this.handles[eventName][i](...params);
}
}
}
$offVmEvent(uid) {
const currentEvents = this.eventMapUid[uid] || [];
currentEvents.forEach((event) => {
this.$off(event);
});
}
$off(eventName) {
delete this.handles[eventName];
}
}
const $EventBus = {};
/* eslint-disable */
$EventBus.install = Vue => {
window.$eventBus = new EventBus(Vue);
Vue.prototype.$eventBus = new EventBus(Vue);
Vue.mixin({
beforeDestroy() {
this.$eventBus.$offVmEvent(this._uid); // eslint-disable-line
},
});
};
Vue.use($EventBus);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment