Juan David Ospina
Juan David Ospina

Reputation: 170

EventBus emitting more than once until page refresh

So I am using the EventBus in Vue.js to send data from one method to another. I have two methods, let's say one() and two(). I am using EventBus as follows:

one() {
  EventBus.$emit("this:that", data);
}

And then I have in my other method something like this

two() {
  EventBus.$on('this:that', data => {
    window.open(data.link, '_blank');
  });
}

When I call the method one() the first time it opens a new tab, however if I call it for a second time it opens twice the same tab, if I call it for the third time it opens three times the same tab and so on until I refresh the page and call it again then it only opens one tab. I tried using EventBus.$once however it didn't open a tab at all.

How would I be able to only open a tab no matter how many times the method is call before refreshing the page. i.e. I call it three times and for the three calls it only generates a new tab each time not one, then two and then three tabs.

Any help would be much appreciated

Upvotes: 1

Views: 986

Answers (2)

Riddhi
Riddhi

Reputation: 2244

Always have a habit of removing event listeners from the event bus that's listening to the event as below.

 beforeDestroy(){
    EventBus.$off('event-bus-name')
  }

Upvotes: 0

bcjohn
bcjohn

Reputation: 2523

I guessed you don't call EventBus.$off("this:that") to unregister your eventBus. So it will be fired increasingly.

Upvotes: 1

Related Questions