Vitaliy Ganzha Vitaliy Ganzha - 5 months ago 15
jQuery Question

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

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


Answer

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" );