ottz0
ottz0

Reputation: 2605

Nuxt - Cannot remove Event Listener

I'm using nuxt.js and have a scroller that scrolls and stops at a fixed point on my page.

When I click to the next page, the method is still looking for the $ref=nav and is coming back undefined because it is not there anymore Cannot read property 'getBoundingClientRect' of undefined

I can add the eventListener but cannot remove the eventListener.

Listener

mounted(){
   window.addEventListener('scroll', this.stickyScroll);
},
beforeDestroy(){
   window.removeEventListener('scroll', this.stickyScroll);
}

Scroller

stickyScroll(){
   window.document.onscroll = () => {
        let navBar = this.$refs.nav;
        let navBarXPosition = navBar.getBoundingClientRect().x;
        let navScrollSpy = this.$refs.navScrollSpy;
        let navScrollSpyXPosition = navScrollSpy.getBoundingClientRect().bottom;
        if(window.scrollY > navBarXPosition && navScrollSpyXPosition > 25){
             this.active = true;
         } else {
             this.active = false;
         }
    }
 },

Upvotes: 0

Views: 1099

Answers (1)

tony19
tony19

Reputation: 138286

window.document.onscroll = fn is effectively the same as window.addEventListener('scroll', fn), so stickyScroll() adds a new event listener for every scroll event.

The solution is to remove the setting of window.document.onscroll so that the contents of the arrow function becomes the contents of stickyScroll, which would allow the proper removal of the handler:

stickyScroll() {
  let navBar = this.$refs.nav;
  let navBarXPosition = navBar.getBoundingClientRect().x;
  let navScrollSpy = this.$refs.navScrollSpy;
  let navScrollSpyXPosition = navScrollSpy.getBoundingClientRect().bottom;
  if (window.scrollY > navBarXPosition && navScrollSpyXPosition > 25) {
    this.active = true;
  } else {
    this.active = false;
  }
}

Upvotes: 2

Related Questions