11 January, 2021

How to fix Duplicate Event Listeners in Vue

Have you ever faced the problem of multiple event listeners for a single emitted event?

As an example, if I say, you have set-up listeners for notifications and instead of displaying notifications once, those are displaying twice, maybe thrice or maybe many times.

Perhaps you would have fixed this issue however by reloading the page or by turning off the event listeners using JS but do you know the reason for this strange behavior of Vuejs?

Let’s understand this phenomenon by taking an example-

You have created a component let’s say Home.vue and on its created hook you have set up a listener using Event Bus, which will be listened to when any event let’s say “display-notification” will be fired.

Your event listener could look like this-

this.EventBus.$on('display-notification', (payload) => {  
   alert(‘Listener is active’);

Now, from somewhere i.e from any other component or from any JS module you are firing the event “display-notification”.This event will be listened to by the Home.vue component for only once, and all is going smooth till here.

Now destroy the Home.vue component by redirecting to some other component’s route, and come back to the route of Home.vue again, and then fire the event “display-notification”. You will get noticed that you are receiving the alert two times. Do you understand why?

That’s the matter of concern to understand, let’s see what is happening here-

  1. At the first time when the component is created, the single listener sets up, and that’s why the emitted event will be listened to by this single listener which will give alert, “Listener is active” only once.
  2. At the time when we switch the route to any other component, the Home.vue component gets destroyed but it’s listeners do not destroy.
  3. When we come back to the route of Home.vue, the component creates again and on it’s created hook, the listener will be set up again. So now this component is having two listeners, the current one and the previous one. If this time you will fire the event “display-notification”, both listeners will listen to this and the result will consist of two alerts there.

That is a glitch which is the cause of the presence of multiple listeners of a single component.If a generic statement can be written, it would be- 

“Every time on component creation the listeners sets up and on component’s destroyment the listeners does not destroy that’s why the recreation(exclude page reloading) of components leads towards the queue of event listeners.”

How to solve this-

The solution is as simple as the strange issue it is.
What you need to do is, turn off the listeners on the component’s destroy hook, which means whenever the component will re-create, no old listener will be there, and the result will always have the single listener for a component.

beforeDestroy() {  

Thanks for reading!

blog comments powered by Disqus