How can I prevent multiple calls from an event listener in a Vue Js Component?

Viewed 792

I am calling a specific function on the event listener like this.

mounted() {
    window.addEventListener("message", this.call);   },

methods: {
    call(e){
       if (e.data === "test"){
          this.call2()
       }
    }
    call2(){
       console.log("called call2")
    }
}

on the first try, call2 is called once. But on the second try, call2 is called twice and will display "called call2" twice on the console. And so on. for every try, it will just add to the number of times call2 is being called in a single action. Is there any way to prevent this?

1 Answers

Always remove event listeners in the beforeDestroy lifecycle hook to prevent leaking listeners.

//Add the event listener
mounted() {
    window.addEventListener("message", this.call);   
},

//Remove the event listener
beforeDestroy() {
    window.removeEventListener("message", this.call);   
},

Have a look at the Vue lifecycle for reference:

enter image description here

Related