How to remove Event Listener in Javascript?

问题: I'm trying to implement lazy scrolling in my script and it's working well up until it reaches the end and I want to stop it from making extra requests. I've added an eve...

问题:

I'm trying to implement lazy scrolling in my script and it's working well up until it reaches the end and I want to stop it from making extra requests.

I've added an event listener to my code using:

window.addEventListener("scroll", _.throttle(checkScroll, 500));

However, when I try to remove it, it still seems to keep listening and acting on the event.

I've tried:

if (json.articles.length == 0) {
                $(".articles").append("<br>That's all folks!");
                window.removeEventListener("scroll", _.throttle(checkScroll, 500));
}

and

if (json.articles.length == 0) {
                $(".articles").append("<br>That's all folks!");
                window.off("scroll");
}

but neither seem to be working.


回答1:

If you add the event listener using plain Javascript, the only way to remove it would be to save a reference to the result of calling _.throttle that you pass to addEventListener:

const handler = _.throttle(checkScroll, 500);
window.addEventListener("scroll", handler);
// ...
window.removeEventListener("scroll", handler);

You could only do something like window.off('scroll') if you also add the handler using jQuery (eg $(window).on(...) and then $(window).off(...)). If you add the handler with Javascript, jQuery's off won't be usable.


回答2:

You can add the event handler in jQuery using on and remove it using off. Here's a fiddle to illustrate it.

$(window).on('scroll', function(ev) { //add handler
    ...
})

$(window).off('scroll', function(ev) { //remove handler
    ...
})
  • 发表于 2018-12-28 19:16
  • 阅读 ( 331 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除