Stop receiving events from destroyed child component

I have a parent where I can dynamically add child components to.

When the child component is added to the mount, I register a listener for the event

EventBus.$on('content-type-saving', function() {
    logic here...
}

      

The problem is that this component is being removed in the parent, removing it from the array of child components, which is still triggered and the code inside it is running.

How can I prevent this? I tried this

    beforeDestroy() {
      //do something before destroying vue instance
        EventBus.$off('content-type-saving')
    }

      

but this turned off this event for all other child components, which means those that were still alive will no longer do logical things because I disabled the event in the destroyed child component.

I thought that disabling the event would only affect the listening for that event for that child component and would not enable the event for all child components.

How can I stop destroyed components from reacting to events?

+3


source to share


2 answers


When you call $off

with only the event name, all listeners are removed for the specified event.

Instead, you want to remove the event only for the listened component. your component should look something like this:



const component = {
  methods:{
    listener(){
      //do something on event
    }
  },
  created(){
    EventBus.$on('content-type-saving', this.listener)
  },
  beforeDestroy(){
    EventBus.$off('content-type-saving', this.listener)
  }
}

      

This will only remove the specific listener for the current component.

+6


source


I would suggest that you are passing the components with some kind of loop that gives them some kind of index. What you could do is push the index to the array and then to the eventBus function. $ Which you would check to check if the index of that component exists in the array (on the parent component) and if it doesn't, run the logic.

EventBus.$emit('content-type-saving', index);

EventBus.$on('content-type-saving', function(index) {
    if(this.deletedComponentArray.indexOf(index) == -1){
        //execute logic
    }
}

      



that's only one way to skin a cat. I'm sure there are other ways to do this as well.

+1


source







All Articles