Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript removeEventListener OnDestroy not working in Angular 6

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?

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);
    }

result:

ERROR TypeError: Cannot read property 'update_collab_visible' of undefined

like image 230
Omar Avatar asked Mar 19 '26 18:03

Omar


2 Answers

Store the callback:

private visibilityChangeCallback: () => void;

ngOnInit() {
    this.visibilityChangeCallback = () => this.handleVisibleState();
    document.addEventListener('visibilitychange', this.visibilityChangeCallback, true);
}

ngOnDestroy() {
    document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
}
like image 109
Frank Modica Avatar answered Mar 21 '26 10:03

Frank Modica


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);
}
like image 29
yurzui Avatar answered Mar 21 '26 09:03

yurzui