5

I'm building the logic for an 'undo delete' - action. For that, I'm using an Event Bus to send an event to two unrelated components like so:

Undo.vue:

EventBus.$emit(`confirm-delete-${this.category}`, this.item.id);

The name of the event(this.category) is based on props coming from a parent (ConfirmDeleteModal.vue) and then received as follows:

CategoryA.vue

created() {
   EventBus.$on('confirm-delete-category-a', (id) => {
     this.confirmDelete(id);
   });
},

CategoryB.vue

created() {
    EventBus.$on('confirm-delete-category-b', (id) => {
      this.confirmDelete(id);
    });
},

My issue: For some reason, the event for category-a is emitted and received twice (category-b works fine). I have to listen to the confirm-event constantly, therefore I can't remove the event listener after I received the event or listen only $once. Any ideas how to solve this (maybe with Vuex)? Thanks!

Houssem
  • 6,409
  • 3
  • 18
  • 28
suuuriam
  • 687
  • 12
  • 24
  • 1
    Probably because `created` runs twice? Did you debug it? Depends on how you use these components. – Estus Flask Feb 25 '20 at 09:11
  • But CategoryA and CategoryB are different components, so `created` doesn't really run twice, does it? – suuuriam Feb 25 '20 at 09:20
  • Since category-a is received twice and category-b is not, there's clearly a difference between A and B somewhere. Please, provide https://stackoverflow.com/help/mcve that can replicate the problem. – Estus Flask Feb 25 '20 at 09:23

1 Answers1

13

I was also facing the same kind of issue and then after some research, I got this solution.

You have defined your component CategoryA.vue two times in your application which is causing the function to run twice which is in this case CategoryA.vue

Solution: You have to call destroyed() after the created() Like:

created() {
    EventBus.$on('confirm-delete-category-a', (id) => {
      this.confirmDelete(id);
    }),
},
destroyed() {
    EventBus.$off('confirm-delete-category-a');
},
Houssem
  • 6,409
  • 3
  • 18
  • 28
Mudassir
  • 398
  • 5
  • 6