window.removeEventListener 命名函数不工作

window.removeEventListener with a named function isn't working

我正在使用 React,下面是我用来实现无限滚动功能的代码。

componentDidMount() {
    // Flag to check if the content has loaded.
    let flag = true;

    function infiniteScroll() {
      let enterpriseWrap = $('.enterprise-blocks');
      let contentHeight = enterpriseWrap.offsetHeight;
      let yOffset = window.pageYOffset;
      let y = yOffset + window.innerHeight;

      console.log('hey');

      if(this.props.hasMore) {

        if(y >= contentHeight && flag) {
          flag = false;

          this.props.loadMoreVendors(function() {
            flag = true;
          });

        }

      } else {
        window.removeEventListener('scroll', infiniteScroll.bind(this));
      }
    }

    window.addEventListener('scroll', infiniteScroll.bind(this));
  }

我实际上想在加载所有项目后取消绑定滚动事件,但 removeEventListener 不起作用。我做错了什么吗?

每次你绑定一个函数,你都会得到一个新的函数。您正在从最初添加的侦听器中删除一个不同的侦听器。存储 function.bind 的结果并在两个地方使用它

this.boundInfiniteScroll = this.infiniteScroll.bind(this);
...

  } else {
    window.removeEventListener('scroll', this.boundInfiniteScroll);
  }
}

window.addEventListener('scroll', this.boundInfiniteScroll);

removeEventListener你必须传递相同的函数引用作为你传递给addEventListener.bind returns新引用因为它是新函数

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

所以在你的例子中,你有两个不同的引用,这就是为什么 removeEventListener 不起作用

let flag = true;
const infiniteScrollFn = infiniteScroll.bind(this);

function infiniteScroll() {
  let enterpriseWrap = $('.enterprise-blocks');
  let contentHeight = enterpriseWrap.offsetHeight;
  let yOffset = window.pageYOffset;
  let y = yOffset + window.innerHeight;

  if (this.props.hasMore) {
    if (y >= contentHeight && flag) {
      flag = false;

      this.props.loadMoreVendors(function() {
        flag = true;
      });
    }
  } else {
    window.removeEventListener('scroll', infiniteScrollFn);
  }
}

window.addEventListener('scroll', infiniteScrollFn);

Example