Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upgrade jQuery to 3.0: rewrite bind() to on() & unbind() to off()

Tags:

jquery

bind() and unbind() were deprecated in jQuery 3.0.0. jQuery Upgrade guide says that API documentation explains how to rewrite them with on() & off(), but I can't find where it explains that.

We have lots of usages of deprecated methods in the app, but majority were upgraded just fine, but there are two cases where it is not clear:

  1. Bind has boolean argument preventBubble argument and we pass false in some cases. How do I achieve same (preventBubble=false) with on()?
  2. We have few usages on unbind where we call unbind(eventName, functionHandler). off() needs selector as second argument in order to pass functionHandler. How do I rewrite that using off()?
like image 607
vmg Avatar asked Nov 02 '25 05:11

vmg


2 Answers

There are two ways to stop an event from bubbling.

Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault().

Or, probably more useful is to call event.stopImmediatePropagation() in the event handler.

As to .off() you can pass only two arguments with the second being the handler function. JQ will assign appropriately and assign undefined to the selector argument. That may or may not work depending on how you specified on.

You might also want to look into namespacing events as it can simplify specifying exactly which events you want to remove. For example (from the documentation)

// Delegate events under the ".validator" namespace
$( "form" ).on( "click.validator", "button", validate );

// Remove event handlers in the ".validator" namespace
$( "form" ).off( ".validator" );
like image 167
DFriend Avatar answered Nov 04 '25 21:11

DFriend


I found an article that describes this, see link and stackoverflow answer

$span_rename_folder
.children()
.children(':image.inplace_cancel')
.off('click')
.on('click', function(){...});

That will remove all click events from the selected element.

like image 43
WSimpson Avatar answered Nov 04 '25 19:11

WSimpson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!