What is the difference between jQuery off () and unbind ()

I used jQuery .bind() and .unbind() to handle the animation event while scrolling.

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

Starting with version 1.7 (I use 1.11), we should use .on() and .off() , but it seems that .off() does not support an event handler that .off() . For ordinary click events and the like, I would need to save the handler in a variable and set up another event handler to detach it (which is against the goal), and for scroll events this is not possible, since .off() requires a selector to detach a specific handler, and scroll events cannot have it.

What is the modern way to do this?

+15
source share
2 answers

What is the modern way to do this?

Use an expression with the function name :

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

.off () requires the selector to untie a specific handler

No no. Just like .on does not require a selector. You only need a selector if you want to cancel the delegated event handler.

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

A selector that must match the first passed to .on () when attaching event handlers.

So, if you did not use it in .on , you do not use it in .off .

+17
source

you can use .on() and .off() like this:

 function scrollHandler(e){ if (myCondition) $(e.target).off('scroll', scrollHandler); } $(window).on('scroll', scrollHandler); 
+1
source

Source: https://habr.com/ru/post/970101/


All Articles