3

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 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.