David Jones
David Jones

Reputation: 10219

Do you have to worry about event duplication when using the "on" function in jQuery?

On projects using older versions of jQuery, I sometimes see things like this:

$(window).unbind("scroll").scroll(infiniteScroll);

I believe this is to prevent duplication of event handlers.

Is this necessary with the newer on function? In other words, is it ever necessary to use off before using on?

$(window).off("scroll").on("scroll", infiniteScroll);

Or is it safe to simply use on even if it might be bound multiple times?

$(window).on("scroll", infiniteScroll);

Upvotes: 0

Views: 47

Answers (1)

forivall
forivall

Reputation: 9901

.on() on its own does not solve the problem, however, it does provide namespaces, which does solve the problem more robustly.

$(window)
    .off(".mynamespacethatisunique")
    .on("scroll.mynamespacethatisunique", infiniteScroll);

Upvotes: 2

Related Questions