Skip to content

Instantly share code, notes, and snippets.

@zecar
Created August 13, 2021 07:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zecar/b59b5cfe08828a8bb82b17a3b045354d to your computer and use it in GitHub Desktop.
Save zecar/b59b5cfe08828a8bb82b17a3b045354d to your computer and use it in GitHub Desktop.
Self-detaching event listener
// The mixin
const EventBus = new Vue()
Vue.mixin({
_EventBusDetachers: []
methods: {
attachEventBusListener(eventName, callback) {
EventBus.$on(eventName, callback)
const detach = () => {
EventBus.$off(eventName, callback)
}
this.$options._EventBusDetachers.push(detach)
},
},
beforeDestroy() {
this.$options._EventBusDetachers.forEach(detach => detach())
},
})
// Setting a listener
const detach = this.attachEventBusListener('some-event', data => {
console.log(data)
})
// Emit from anywhere
EventBus.$emit('some-event', {
works: true
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment