[SalesForce] Event listener being attached to lightning component everytime it loads

I have an iframe inside a lightning component that calls window.top.postMessage("data", "*");.

When my lightning component loads it adds an event listener of message to listen to this post

window.addEventListener('message', triggerEvent, false)

The problem here is that, when you leave the Lightning component in mobile and you go back to it, a new event listener is added, so that means when the window.top.postMessage("data", "*"); event fires, it fires twice, and if you open up the lightning component again, it fires 3 times, then 4 and so on.

I do not want to remove this event listener once it fires because i need to keep it for the entirety of the lightning components life. I have also tried to remove the event listener once the component undrenders by over riding the unrender functin, and it doesnt work.

How can I have the event listener fire only once but also keep it?

Best Answer

The solution to this was having the function that the event listener binds to be a helper function.

window.addEventListener('message', helper.MyMethod, false);

mycomponentHelper.js

MyMethod: function(event){
    // handle event listener here
}
Related Topic