I have been experimenting with using the removeEventListener
function in my Angular component. I came across a helpful discussion on this topic: Javascript removeEventListener not working
...
ngOnInit() {
document.addEventListener('visibilitychange', () =>this.handleVisibleState(), true);
}
ngOnDestroy() {
document.removeEventListener('visibilitychange', () => this.handleVisibleState(), true);
}
handleVisibleState() {
let vis = document.visibilityState === 'visible';
this.configsService.update_collab_visible(vis);
}
...
The issue I encountered is that the addEventListener
continues to work even after ngOnDestroy()
is called.
Can anyone provide guidance on how to properly unbind visibilityState from the document within Angular components?
attempt 2
private visibilityChangeCallback: () => void;
ngOnInit() {
this.visibilityChangeCallback = () => this.handleVisibleState();
document.addEventListener('visibilitychange', this.handleVisibleState, true);
}
ngOnDestroy() {
document.removeEventListener('visibilitychange', this.handleVisibleState, true);
}
handleVisibleState() {
let vis = document.visibilityState === 'visible';
console.log(typeof this.configsService); // undefined
this.configsService.update_collab_visible(vis);
}
After implementing these changes, I encountered the following error:
ERROR TypeError: Cannot read property 'update_collab_visible' of undefined