Skip to content

Instantly share code, notes, and snippets.

@xiaoliang2233
Last active August 6, 2017 05:21
Show Gist options
  • Save xiaoliang2233/325cc8015adfb9aa875ab761a7e28296 to your computer and use it in GitHub Desktop.
Save xiaoliang2233/325cc8015adfb9aa875ab761a7e28296 to your computer and use it in GitHub Desktop.
event bus for vue
import Vue from "vue"
import * as constants from "./event-constant"
const eventMap = new Map()
const eventBus = {
data() {
return {
eventMap,
registerEvent: {
}
}
},
methods: {
subscribe(event, callback) {
if (!constants[event]) throw new TypeError(`expect define constant before subscribe`);
if (!this.eventMap.has(event)) this.initEvent(event);
this.eventMap.get(event).add(callback);
callback(this.registerEvent['event']);
},
broadcast(event, value) {
if (!constants[event]) throw new TypeError(`expect define constant before broadcast`);
if (!this.eventMap.has(event)) this.initEvent(event)
this.$set(this.registerEvent, event, value);
},
initEvent(event) {
this.eventMap.set(event, new Set());
this.$set(this.registerEvent, event, null);
this.$on(event, value => {
this.eventMap.get(event).forEach(callback => callback(value))
})
this.$watch(`registerEvent.${event}`, function(value) {
this.$emit(event, value);
})
}
}
}
export default new Vue(eventBus);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment