JavaScript:删除事件监听器不起作用

标签 javascript addeventlistener debouncing removeeventlistener

我想使用 JavaScript 删除事件监听器,但它似乎不起作用...我尝试将 debounce 以及 showPopup 函数作为参数传递给 removeEventListener.

const elementToListenForScroll = document.querySelector('.howitworks__mainheading');
const distanceToTop = elementToListenForScroll.getBoundingClientRect().top;

function debounce(func, wait = 20, immediate = true) {
  var timeout;
  return function() {
    var context = this,
        args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
}

function showPopup() {
  const currentScrollPosition = window.scrollY;
  if (currentScrollPosition > distanceToTop) {
    console.log('hey it works');
    window.removeEventListener('scroll', debounce);
  }
}

window.addEventListener('scroll', debounce(showPopup));

最佳答案

debounce(showPopup)debounce 不同。

debounce(showPopup) 调用在 debounce 仅引用该函数时执行代码。

为了能够removeEventListener,您需要传递与传递给addEventListener相同的函数引用。

debounce(showPopup) 分配给某个变量并将其用于事件订阅/取消订阅。

示例:

    const elementToListenForScroll = 
    document.querySelector('.howitworks__mainheading');
    const distanceToTop = elementToListenForScroll.getBoundingClientRect().top;
    

    var realReference =  debounce(showPopup);
    function debounce(func, wait = 20, immediate = true) {
      var timeout;
      return function() {
      var context = this, args = arguments;
      var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
    };
    }
    
    function showPopup() {
      const currentScrollPosition = window.scrollY;
      if(currentScrollPosition > distanceToTop) {
        console.log('hey it works');
        window.removeEventListener('scroll', realReference);
      }
    }
    
    window.addEventListener('scroll', realReference);

关于JavaScript:删除事件监听器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54552782/

相关文章:

javascript - 将 http 请求中定义的范围变量从 Controller 传递到指令

javascript - jQuery 表过滤器排序不正确

javascript - AddEventListener 未附加(单击按钮时没有任何反应)

javascript - 去抖不起作用

angular - 如何在搜索键上实现去抖时间

javascript - ASP.NET MVC 将 json 数组作为常规发布请求提交给 Controller (nonajax)

javascript - 选择一个元素数组并使用它们

创建另一个事件监听器时,Javascript 事件监听器消失

javascript - 通过 Post 动态添加点击事件监听器到 Div 元素时递归过多

android - react native 使用 debounce 在 android 设备上不起作用