Every time I create an angular controller, I add an event listener. However, when I return to the page after leaving it, a new event listener is added because the constructor is called again.
Unfortunately, when this event is triggered, it gets invoked multiple times - twice, thrice, and so on as I keep leaving and coming back. My intention is for it to be invoked only once.
Below is the code snippet where I add the event listener along with the function it calls: (For your information, I am using TypeScript)
In Constructor:
this.$window.addEventListener("message", this.processApi, false);
Function Called:
processApi = (e) => {
this.processApiMessage(e.data);
};
I've come across suggestions to use a reference to a function rather than writing it out directly to ensure that both refer to the same instance of a function. However, even with this approach, the same event listener is being called multiple times.
Upon inspecting Chrome's Developer Tools and navigating to Event Listeners, specifically the message section, I notice a new Window element every time the constructor is executed. While I can manually remove each Event Listener via developer tools, I encounter issues doing so in the code by calling:
this.$window.removeEventListener("message", this.processApi, false);
Refreshing the page clears all event listeners and recreates the one in the constructor, which resolves the issue temporarily.
Within my angular setup, I initially used the $location service to navigate to the URL linked to my controller. As a quick fix to ensure that the event listener is hit only once, I replaced $location.url("url") with window.location.href("url"). This method seems effective as the page refreshes upon navigation. However, I prefer sticking to utilizing the $location service for routing while ensuring that my event listener is triggered just once despite the repeated invocation of the angular constructor.