Last active
May 14, 2020 23:45
-
-
Save vinicius73/fdb82e0ba94e19366676880be94b2bca to your computer and use it in GitHub Desktop.
Vue.js EventBus approach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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