Skip to content

Instantly share code, notes, and snippets.

@vinicius73
Last active May 14, 2020 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinicius73/fdb82e0ba94e19366676880be94b2bca to your computer and use it in GitHub Desktop.
Save vinicius73/fdb82e0ba94e19366676880be94b2bca to your computer and use it in GitHub Desktop.
Vue.js EventBus approach
const listeners = ctx => {
if (!ctx.$options.on) {
return
}
const listeners = {}
Object.entries(ctx.$options.on)
.forEach(([event, callback]) => {
listeners[event] = callback.bind(ctx)
ctx.$root.$on(event, listeners[event])
})
Object.defineProperty(ctx, '$_events', Object.freeze(listeners))
}
const useMessageBroker = {
created () {
listeners(this)
const $dispatch = (...args) => this.$root.$emit(...args)
Object.defineProperty(this, '$dispatch', {
get: () => $dispatch
})
},
beforeDestroy () {
Object.entries(this.$_events || {})
.forEach(([event, callback]) => {
this.$root.$off(event, callback)
})
}
}
export { useMessageBroker }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment