Vitaliy Ganzha Vitaliy Ganzha - 1 year ago 84
jQuery Question

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

() and
() were deprecated in jQuery 3.0.0.
jQuery Upgrade guide says that API documentation explains how to rewrite them with
, 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
    argument and we pass false in some cases. How do I achieve same (
    ) with

  2. We have few usages on unbind where we call
    unbind(eventName, functionHandler)
    needs selector as second argument in order to pass
    . How do I rewrite that using

Answer Source

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" );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download