Javascript removeEventListener OnDestroy not working in Angular 6











up vote
0
down vote

favorite












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











share|improve this question




























    up vote
    0
    down vote

    favorite












    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











    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      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











      share|improve this question















      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








      angular typescript angular-routing






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 10 hours ago

























      asked 10 hours ago









      Omar

      8971123




      8971123
























          4 Answers
          4






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          Store the callback:



          private visibilityChangeCallback: () => void;

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

          ngOnDestroy() {
          document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
          }





          share|improve this answer























          • I guess self.handleVisibleState() should be this.handleVisibleState()
            – Sunil Singh
            10 hours ago










          • see my question. I added why that didnt work
            – Omar
            9 hours ago










          • In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.
            – Frank Modica
            9 hours ago










          • @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.
            – Frank Modica
            9 hours ago


















          up vote
          2
          down vote













          You have to make the function a property field on the class with an arrow function and not use an anonymous function, because the function reference won't be the same.



          The reason you are getting the Cannot read property 'update_collab_visible' of undefined error is because you are using a class function instead of a class field. This will move the this context to the function, which is not what you want:



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


          There are also other options. I see you want to use the capture flag for the event. You can think of using rxjs lib as well:



          destroy = new Subject<void>();

          ngOnInit() {
          fromEvent(document, 'visibilitychange', true).pipe(
          takeUntil(this.destroy)
          ).subscribe((event) => this.handleVisibleState(event));
          }

          ngOnDestroy() {
          this.destroy.next();
          this.destroy.complete();
          }


          advertisement



          There is also an angular library which adds functionality to the template and component event binding called ng-event-options. If you have installed/imported that, you can simply use:



          @HostListener('document:visibilitystate.c')
          handleVisibleState() {
          let vis = document.visibilityState === 'visible';
          this.configsService.update_collab_visible(vis);
          }


          and you're done






          share|improve this answer























          • the last one will destroy automatically?
            – Omar
            9 hours ago










          • @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually
            – PierreDuc
            9 hours ago












          • I dont understand how the 3rd option's listener is registered?
            – Omar
            9 hours ago










          • @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does
            – PierreDuc
            9 hours ago




















          up vote
          1
          down vote













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





          share|improve this answer




























            up vote
            0
            down vote













            This reason why this.<anything> doesn't work is because the meaning of this is different since it's within a callback and you're not binding it.



            If you bind this it should work.



            document.addEventListener('visibilitychange', this.handleVisibleState.bind(this), true);






            share|improve this answer

















            • 1




              The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.
              – Frank Modica
              9 hours ago











            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53343747%2fjavascript-removeeventlistener-ondestroy-not-working-in-angular-6%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            4 Answers
            4






            active

            oldest

            votes








            4 Answers
            4






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            Store the callback:



            private visibilityChangeCallback: () => void;

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

            ngOnDestroy() {
            document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
            }





            share|improve this answer























            • I guess self.handleVisibleState() should be this.handleVisibleState()
              – Sunil Singh
              10 hours ago










            • see my question. I added why that didnt work
              – Omar
              9 hours ago










            • In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.
              – Frank Modica
              9 hours ago










            • @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.
              – Frank Modica
              9 hours ago















            up vote
            1
            down vote



            accepted










            Store the callback:



            private visibilityChangeCallback: () => void;

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

            ngOnDestroy() {
            document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
            }





            share|improve this answer























            • I guess self.handleVisibleState() should be this.handleVisibleState()
              – Sunil Singh
              10 hours ago










            • see my question. I added why that didnt work
              – Omar
              9 hours ago










            • In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.
              – Frank Modica
              9 hours ago










            • @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.
              – Frank Modica
              9 hours ago













            up vote
            1
            down vote



            accepted







            up vote
            1
            down vote



            accepted






            Store the callback:



            private visibilityChangeCallback: () => void;

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

            ngOnDestroy() {
            document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
            }





            share|improve this answer














            Store the callback:



            private visibilityChangeCallback: () => void;

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

            ngOnDestroy() {
            document.removeEventListener('visibilitychange', this.visibilityChangeCallback, true);
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 10 hours ago

























            answered 10 hours ago









            Frank Modica

            5,8112725




            5,8112725












            • I guess self.handleVisibleState() should be this.handleVisibleState()
              – Sunil Singh
              10 hours ago










            • see my question. I added why that didnt work
              – Omar
              9 hours ago










            • In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.
              – Frank Modica
              9 hours ago










            • @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.
              – Frank Modica
              9 hours ago


















            • I guess self.handleVisibleState() should be this.handleVisibleState()
              – Sunil Singh
              10 hours ago










            • see my question. I added why that didnt work
              – Omar
              9 hours ago










            • In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.
              – Frank Modica
              9 hours ago










            • @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.
              – Frank Modica
              9 hours ago
















            I guess self.handleVisibleState() should be this.handleVisibleState()
            – Sunil Singh
            10 hours ago




            I guess self.handleVisibleState() should be this.handleVisibleState()
            – Sunil Singh
            10 hours ago












            see my question. I added why that didnt work
            – Omar
            9 hours ago




            see my question. I added why that didnt work
            – Omar
            9 hours ago












            In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.
            – Frank Modica
            9 hours ago




            In your edit, you're still doing document.addEventListener('visibilitychange', this.handleVisibleState, true);.
            – Frank Modica
            9 hours ago












            @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.
            – Frank Modica
            9 hours ago




            @Omar My answer essentially does what @PierreDuc's first suggestion does, but my answer creates a separate function so you don't have to change the class method handleVisibleState to an arrow function. If you don't care about that, @PierreDuc's change is simpler.
            – Frank Modica
            9 hours ago












            up vote
            2
            down vote













            You have to make the function a property field on the class with an arrow function and not use an anonymous function, because the function reference won't be the same.



            The reason you are getting the Cannot read property 'update_collab_visible' of undefined error is because you are using a class function instead of a class field. This will move the this context to the function, which is not what you want:



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


            There are also other options. I see you want to use the capture flag for the event. You can think of using rxjs lib as well:



            destroy = new Subject<void>();

            ngOnInit() {
            fromEvent(document, 'visibilitychange', true).pipe(
            takeUntil(this.destroy)
            ).subscribe((event) => this.handleVisibleState(event));
            }

            ngOnDestroy() {
            this.destroy.next();
            this.destroy.complete();
            }


            advertisement



            There is also an angular library which adds functionality to the template and component event binding called ng-event-options. If you have installed/imported that, you can simply use:



            @HostListener('document:visibilitystate.c')
            handleVisibleState() {
            let vis = document.visibilityState === 'visible';
            this.configsService.update_collab_visible(vis);
            }


            and you're done






            share|improve this answer























            • the last one will destroy automatically?
              – Omar
              9 hours ago










            • @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually
              – PierreDuc
              9 hours ago












            • I dont understand how the 3rd option's listener is registered?
              – Omar
              9 hours ago










            • @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does
              – PierreDuc
              9 hours ago

















            up vote
            2
            down vote













            You have to make the function a property field on the class with an arrow function and not use an anonymous function, because the function reference won't be the same.



            The reason you are getting the Cannot read property 'update_collab_visible' of undefined error is because you are using a class function instead of a class field. This will move the this context to the function, which is not what you want:



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


            There are also other options. I see you want to use the capture flag for the event. You can think of using rxjs lib as well:



            destroy = new Subject<void>();

            ngOnInit() {
            fromEvent(document, 'visibilitychange', true).pipe(
            takeUntil(this.destroy)
            ).subscribe((event) => this.handleVisibleState(event));
            }

            ngOnDestroy() {
            this.destroy.next();
            this.destroy.complete();
            }


            advertisement



            There is also an angular library which adds functionality to the template and component event binding called ng-event-options. If you have installed/imported that, you can simply use:



            @HostListener('document:visibilitystate.c')
            handleVisibleState() {
            let vis = document.visibilityState === 'visible';
            this.configsService.update_collab_visible(vis);
            }


            and you're done






            share|improve this answer























            • the last one will destroy automatically?
              – Omar
              9 hours ago










            • @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually
              – PierreDuc
              9 hours ago












            • I dont understand how the 3rd option's listener is registered?
              – Omar
              9 hours ago










            • @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does
              – PierreDuc
              9 hours ago















            up vote
            2
            down vote










            up vote
            2
            down vote









            You have to make the function a property field on the class with an arrow function and not use an anonymous function, because the function reference won't be the same.



            The reason you are getting the Cannot read property 'update_collab_visible' of undefined error is because you are using a class function instead of a class field. This will move the this context to the function, which is not what you want:



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


            There are also other options. I see you want to use the capture flag for the event. You can think of using rxjs lib as well:



            destroy = new Subject<void>();

            ngOnInit() {
            fromEvent(document, 'visibilitychange', true).pipe(
            takeUntil(this.destroy)
            ).subscribe((event) => this.handleVisibleState(event));
            }

            ngOnDestroy() {
            this.destroy.next();
            this.destroy.complete();
            }


            advertisement



            There is also an angular library which adds functionality to the template and component event binding called ng-event-options. If you have installed/imported that, you can simply use:



            @HostListener('document:visibilitystate.c')
            handleVisibleState() {
            let vis = document.visibilityState === 'visible';
            this.configsService.update_collab_visible(vis);
            }


            and you're done






            share|improve this answer














            You have to make the function a property field on the class with an arrow function and not use an anonymous function, because the function reference won't be the same.



            The reason you are getting the Cannot read property 'update_collab_visible' of undefined error is because you are using a class function instead of a class field. This will move the this context to the function, which is not what you want:



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


            There are also other options. I see you want to use the capture flag for the event. You can think of using rxjs lib as well:



            destroy = new Subject<void>();

            ngOnInit() {
            fromEvent(document, 'visibilitychange', true).pipe(
            takeUntil(this.destroy)
            ).subscribe((event) => this.handleVisibleState(event));
            }

            ngOnDestroy() {
            this.destroy.next();
            this.destroy.complete();
            }


            advertisement



            There is also an angular library which adds functionality to the template and component event binding called ng-event-options. If you have installed/imported that, you can simply use:



            @HostListener('document:visibilitystate.c')
            handleVisibleState() {
            let vis = document.visibilityState === 'visible';
            this.configsService.update_collab_visible(vis);
            }


            and you're done







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 9 hours ago

























            answered 10 hours ago









            PierreDuc

            27.5k45173




            27.5k45173












            • the last one will destroy automatically?
              – Omar
              9 hours ago










            • @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually
              – PierreDuc
              9 hours ago












            • I dont understand how the 3rd option's listener is registered?
              – Omar
              9 hours ago










            • @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does
              – PierreDuc
              9 hours ago




















            • the last one will destroy automatically?
              – Omar
              9 hours ago










            • @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually
              – PierreDuc
              9 hours ago












            • I dont understand how the 3rd option's listener is registered?
              – Omar
              9 hours ago










            • @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does
              – PierreDuc
              9 hours ago


















            the last one will destroy automatically?
            – Omar
            9 hours ago




            the last one will destroy automatically?
            – Omar
            9 hours ago












            @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually
            – PierreDuc
            9 hours ago






            @Omar yes because it uses the library, and when the component gets destroyed every event with HostListener is removed. It's the same as using an event binding in your template. You also do not need to remove that manually
            – PierreDuc
            9 hours ago














            I dont understand how the 3rd option's listener is registered?
            – Omar
            9 hours ago




            I dont understand how the 3rd option's listener is registered?
            – Omar
            9 hours ago












            @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does
            – PierreDuc
            9 hours ago






            @Omar read about @HostListener. It's an angular decorator to bind events on the component. But if you use document:, or window: or body:, it binds to that element. After that comes the event name. The ng-event-options adds the possibility for extra event options like capture (and a bunch more). This is set by single characters. In this case the c stands for capture, which is what your true in your addEventListener does
            – PierreDuc
            9 hours ago












            up vote
            1
            down vote













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





            share|improve this answer

























              up vote
              1
              down vote













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





              share|improve this answer























                up vote
                1
                down vote










                up vote
                1
                down vote









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





                share|improve this answer












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






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 9 hours ago









                yurzui

                90.3k10176199




                90.3k10176199






















                    up vote
                    0
                    down vote













                    This reason why this.<anything> doesn't work is because the meaning of this is different since it's within a callback and you're not binding it.



                    If you bind this it should work.



                    document.addEventListener('visibilitychange', this.handleVisibleState.bind(this), true);






                    share|improve this answer

















                    • 1




                      The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.
                      – Frank Modica
                      9 hours ago















                    up vote
                    0
                    down vote













                    This reason why this.<anything> doesn't work is because the meaning of this is different since it's within a callback and you're not binding it.



                    If you bind this it should work.



                    document.addEventListener('visibilitychange', this.handleVisibleState.bind(this), true);






                    share|improve this answer

















                    • 1




                      The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.
                      – Frank Modica
                      9 hours ago













                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    This reason why this.<anything> doesn't work is because the meaning of this is different since it's within a callback and you're not binding it.



                    If you bind this it should work.



                    document.addEventListener('visibilitychange', this.handleVisibleState.bind(this), true);






                    share|improve this answer












                    This reason why this.<anything> doesn't work is because the meaning of this is different since it's within a callback and you're not binding it.



                    If you bind this it should work.



                    document.addEventListener('visibilitychange', this.handleVisibleState.bind(this), true);







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 9 hours ago









                    mwilson

                    2,57731846




                    2,57731846








                    • 1




                      The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.
                      – Frank Modica
                      9 hours ago














                    • 1




                      The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.
                      – Frank Modica
                      9 hours ago








                    1




                    1




                    The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.
                    – Frank Modica
                    9 hours ago




                    The OP would still need to store the result of this.handleVisibleState.bind(this) to pass it to removeEventListener.
                    – Frank Modica
                    9 hours ago


















                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53343747%2fjavascript-removeeventlistener-ondestroy-not-working-in-angular-6%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                    Alcedinidae

                    Origin of the phrase “under your belt”?