16

removeEventListener() works when I don't use throttle() from lodash.

   window.addEventListener('scroll', this.checkVisible, 1000, false);
     window.removeEventListener('scroll', this.checkVisible, 1000, false);

(I bound the method in the constructor)


Unfortunately, with the throttle(this.checkVisible) function wrapped around it - doesn't work. I assume it's because when trying to remove the listener, throttle() makes new instance and maybe I should bind it globally. How though (if that's the case)?

  import React from 'react';
    import throttle from 'lodash.throttle';
    
    class About extends React.Component {
      constructor(props) {
        super(props);
    
        this.checkVisible = this.checkVisible.bind(this);
      }
    
      componentDidMount() {
        window.addEventListener('scroll', throttle(this.checkVisible, 1000), false);
    
      }
    
      checkVisible() {
       if (window.scrollY > 450) {
        // do something
        window.removeEventListener('scroll', throttle(this.checkVisible, 1000),
        false);
        }
      }
    
      render() {
        return (
          <section id="about"> something
          </section>
        );
      }
    }
    
    export default About;
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sebastian
  • 1,225
  • 1
  • 16
  • 27

1 Answers1

24

Lodash trottle creates a throttled function so you need to store a reference to it in order to remove the eventlistener.

import React from 'react';
import throttle from 'lodash.throttle';

class About extends React.Component {
  constructor(props) {
    super(props);

    this.checkVisible = this.checkVisible.bind(this);
    // Store a reference to the throttled function
    this.trottledFunction = throttle(this.checkVisible, 1000);
  }

  componentDidMount() {
    // Use reference to function created by lodash throttle
    window.addEventListener('scroll', this.trottledFunction, false);

  }

  checkVisible() {
   if (window.scrollY > 450) {
    // do something
    window.removeEventListener('scroll', this.trottledFunction, false);
    }
  }

  render() {
    return (
      <section id="about"> something
      </section>
    );
  }
}

export default About;
lagerone
  • 1,747
  • 13
  • 13
  • 1
    Thank you for this answer! I've been stuck on a problem just like this all day. – chipcullen Nov 02 '18 at 20:17
  • 3
    This bothered me so much, I also wrote up a blog post about it - https://chipcullen.com/troubleshooting-adding-and-removing-eventlisteners/ - thank you again, @lagerone – chipcullen Nov 03 '18 at 12:18
  • hi, can you tell how this will work with functional components – Always_a_learner Jul 22 '20 at 06:59
  • @Harsimer You will have to use hooks to achieve this with functional components. something like https://stackoverflow.com/a/62017005/975720. – lagerone Jul 22 '20 at 08:36