Benny
Benny

Reputation: 879

Prevent $emit from emitting more than once in Vue

I have an emit call within my Vue project to update search results, but the emit is being called at least 4 times, because the emit call is defined at various spots, so the data is sometimtes emitted with it and at other spots it is not.

I am using a global bus to perform an emit.

this.$root.bus.$emit('resetValuesInInfiniteLoader', filteredEntities);

this.$root.bus.$on('resetValuesInInfiniteLoader', function (filteredEntities) {});

I tried to name the emits calls differently, and also tried to use a different global vue bus but both options did not really work well. Any idea how I can do this in an efficient manner so that the $emit is always only called once? How do I need to set it up to ensure that the emit is always only called once? I also tried using $once, which did not work, or tried to destroy the $emit. Can someone give me a small fiddle example or so maybe so I understand how to do this in the right way?

Upvotes: 2

Views: 5400

Answers (2)

Benny
Benny

Reputation: 879

I went with using vuex store, it seems a lot easier to communicate with any component within the application, has the advantage of global communication, yet does not have the caveat of sending multiple actions such as emit events

Upvotes: 0

Andrew1325
Andrew1325

Reputation: 3579

I have found this to be the case also and feel that there are some problems with using it in multiple locations. My understanding is that global event busses are not recommended in most applications as they can lead to a confusing tangle of events. The recommendation is that you use a state management solution like vuex.

But anyway, just a couple of points with your code above. I don't know how you created your bus but I have known to create it as such:

//main.js

const EventBus = new Vue()
Object.defineProperties(Vue.prototype, {
  $bus: {
    get: function () {
      return EventBus
    }
  }
})

This creates it and makes it global. It can then be triggered in a component or components with:

<button @click="$bus.$emit('my-event')">click</button>

or

methods: {
    triggerMyEvent () {
      this.$bus.$emit('my-event', { ... pass some event data ... })
    }
  }

and listened to:

created () {
            this.$bus.$on('my-event', ($event) => {
                console.log('My event has been triggered', $event)
                this.eventItem = 'Event has now been triggered'
                //this.$bus.$off('my-event')
            })

        },

I have found that it works sometimes. I don't know why but it will work then it will trigger several events and I think it is because it isn't finalised or something. You may note I have commented out this.$bus.off which certainly stops it but it then doesn't work again. So I don't know what that's all about.

So there you go, a total non-answer, as in, Yes I've had that too, No I cant fix it.

Upvotes: 1

Related Questions