Created
August 13, 2021 07:17
-
-
Save zecar/b59b5cfe08828a8bb82b17a3b045354d to your computer and use it in GitHub Desktop.
Self-detaching event listener
This file contains 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
// 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