I have a situation where every time I create an Angular component, an event listener is added. However, upon leaving the page and returning to it, a new event listener is added because the constructor is called again.
The problem arises when this event is triggered - it gets invoked multiple times, increasing with each visit back to the page. My intention is for it to be invoked only once.
My framework of choice is Angular14.
Within the constructor (I've also tried using ngOnInit), I have included:
if (window.addEventListener) {
window.addEventListener('message', this.test.bind(this));
}
else {
(<any>window).attachEvent('onmessage', this.test.bind(this));
}
Here's my callback function:
test(event: any): void {
if (event.data !== undefined) {
if (event.data.msg === 'test') {
return;
}
if (event.data.msg === 'check') {
this.dosomething();
}
}
}
In ngOnDestroy, I attempt to remove the event listener:
ngOnDestroy(): void{
window.removeEventListener('message', this.test);
(<any>window).removeEventListener('onmessage', this.test);
}
Despite these efforts, the issue persists and dosomething is called multiple times on revisiting the component. Any insights or suggestions would be greatly appreciated.
I even tried removing the event listener upon receiving eventdata like so:
if (event.data.msg === 'check') {
window.removeEventListener('message', this.test);
(<any>window).removeEventListener('onmessage', this.test);
this.dosomething();
}
Unfortunately, this approach did not work as expected.