在React中删除事件侦听器(lodash.throttle)

时间:2017-10-29 16:22:59

标签: javascript reactjs events javascript-events

嘿stackoverflowers,

removeEventListener()在我不使用lodash的throttle()时有效。

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

(我绑定了构造函数中的方法)

不幸的是,throttle(this.checkVisible)函数缠绕着它 - 不起作用。我假设它是因为在尝试删除监听器时,throttle()创建了新实例,也许我应该全局绑定它。怎么样(如果是这样的话)?

  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;

谢谢,善意的人!

1 个答案:

答案 0 :(得分:11)

Lodash trottle创建一个限制函数,因此您需要存储对它的引用才能删除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;