Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
61
rated 0 times [  63] [ 2]  / answers: 1 / hits: 22533  / 10 Years ago, fri, may 30, 2014, 12:00:00

I was using jQuery .bind() and .unbind() to handle an animation event on scroll.



$(window).bind('scroll', function(){
... code ...
if(code_was_successful){
$(window).unbind(e);
}
});


As of 1.7 (I'm using 1.11) we're supposed to use .on() and .off(), but .off() seems to have no support for an event handler unbinding itself. For normal click events and such, I'd have to save the handler to a variable and set up another event handler to unbind it (which defeats the purpose), and for scroll events it's impossible since .off() requires a selector to unbind a specific handler, and scroll events can't have one.



What's the modern way to do this?


More From » jquery

 Answers
36

What's the modern way to do this?




Use a named function expression:



$(window).on('scroll', function handler(){
... code ...
if(code_was_successful){
$(window).off('scroll', handler);
}
});



.off() requires a selector to unbind a specific handler




No it does not. Just like .on doesn't require a selector. You only need the selector if you want to unbind a delegated event handler.



As you can read in the documentation of .off about the selector argument:




A selector which should match the one originally passed to .on() when attaching event handlers.




So if you didn't use one in .on, you don't use one in .off.


[#70784] Thursday, May 29, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gregorio

Total Points: 362
Total Questions: 95
Total Answers: 93

Location: Puerto Rico
Member since Sun, Jun 27, 2021
3 Years ago
;