问题描述:

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()?

网友答案:

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" );
网友答案:

Selector as second argument is optional for setting a delegation target. Since this isn't how your bind() would be set up it isn't an issue

bind() uses on() internally, you should be able to simply rename bind to on

网友答案:

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.

相关阅读:
Top