I am trying to removeEventListener in my angular compenent: 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);
}
...
with the above addEventListener works even after ngOnDestroy ()
How can I unbind visibilityState from document in angular components?
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);
}
result:
ERROR TypeError: Cannot read property 'update_collab_visible' of undefined
Store the callback:
private visibilityChangeCallback: () => void;
ngOnInit() {
this.visibilityChangeCallback = () => this.handleVisibleState();
document.addEventListener('visibilitychange', this.visibilityChangeCallback, true);
}
ngOnDestroy() {
document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
}
Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect. You're passing other function to that.
Using instance arrow function should help in your case:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With