rut2
rut2

Reputation: 706

eventBus is listening duplicate events when component is loaded multiple times

I am facing very important and weird issue with vue.js eventBus.

My code is something like this,

mounted: function() {
    eventBus.$on('load-item', () => {
        // some loading data ajax 
    })
}

So, if I go first time in this component, it will execute only one time. But if I switch to other component and then again come back to this component, the event is emitting one time but the listener is executing this function 2 times. so every time I visit this component it is increasingly loading data. Third time 3 Ajax request. 4th time 4 ajax and so on.

I have tried following solution,

beforeDestroy: function () {
    eventBus.$off('load-item');
}

So above code will remove the listener, is it working only when it destroy the component. But in my case, if another view is using the same component then the same issue occurs.

My question is, what is the best way to remove event listener completely when we change page?

is there anything already there in vue.js?

I can explain in details if you are not clear about it.

Upvotes: 4

Views: 7202

Answers (2)

manbok lee
manbok lee

Reputation: 11

If unique event name. It can be applied as follows

mounted: function() {
    if (!eventBus._events['load-item']) {
        eventBus.$on('load-item', () => {
            // some loading data ajax 
        })
    }
}

However, I know that using vuex is better than using event bus.

Upvotes: 1

Kevin Batongbakal
Kevin Batongbakal

Reputation: 533

Maybe you need eventBus.$once instead of eventBus.$on When using $once after it's been executed it'll no longer called unless it was initialised again

Upvotes: 15

Related Questions