drake035
drake035

Reputation: 2897

How to remove a listener bound to an anonymous function?

In my component I have a listener attached to an anonymous function.

Hw can I remove that listener later on since there's no function name to designate the function attached to it?

mounted() {
  EventBus.$on('setStickyHeaderCaption', (payload) => {
    ...
  });
},
beforeDestroy() {
  EventBus.$off('setStickyHeaderCaption');
}

Upvotes: 0

Views: 180

Answers (3)

Estus Flask
Estus Flask

Reputation: 223104

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.

Upvotes: 0

Radu Diță
Radu Diță

Reputation: 14201

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);
}

Upvotes: 1

Ohgodwhy
Ohgodwhy

Reputation: 50798

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.

Upvotes: 0

Related Questions