简体   繁体   中英

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 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.

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.

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
    ...
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM