0👍
✅
You can’t.
There’s no way to definitively determine which listener you’d destroy because, as you put it, you used an anonymous function as the callback.
1👍
Without saving a reference to the function there is no way.
You can do something like this:
mounted() {
this.anon = (payload) => {
...
}
EventBus.$on('setStickyHeaderCaption', this.anon);
},
beforeDestroy() {
EventBus.$off('setStickyHeaderCaption', this.anon);
}
0👍
Event listener is usually identified by a function that was provided. If a function is anonymous, a listener cannot be removed.
This is the case for Vue method. Methods are already bound to Vue instance and don’t need to be arrows:
methods: {
setStickyHeaderCaptionHandler(payload) {...}
},
mounted() {
EventBus.$on('setStickyHeaderCaption', this.setStickyHeaderCaptionHandler);
},
beforeDestroy() {
EventBus.$off('setStickyHeaderCaption', this.setStickyHeaderCaptionHandler);
}
That methods are accessible outside the component and can be spied or mocked also makes testing easier.
Source:stackexchange.com