Web App Development

What's the relationship between jQuery bind/unbind and on/off?

The on/off methods were introduced with jQuery 1.7 in November 2011. They supersede methods like bind/unbind, live/die and delegate/undelegate. So bind/unbind now map to on and off:

bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
}

The additional argument for the on/off method is the selector argument, which makes delegated events possible.
(Delegated events are bound to a parent element rather than the element that we want to handle the event for. So for example you can attach a click event to all buttons inside a div without having to add an event handler whenever a button is added. In this example on would be called on the div and the selector argument would be "button".
Once you've done that jQuery will handle click events on the div and check whether the original target element of the event or one of its parents is matched by the selector.)

Future of bind/unbind

While live and die are deprecated, bind and unbind are merely "preferred for attaching and removing event handlers".

Some internals...

Internally the on method maps to jQuery.event.add. That function then actually adds a handler to the event using addEventListener (or attachEvent in IE).
When the event is triggered the handler calls jQuery.event.dispatch which will call all the event handlers you've added.

Comments


Follow me on Twitter
I'm building monitoring tool for site speed and Core Web Vitals.
➔ Start monitoring your website or run a free site speed test