Jquery's .Bind() VS. .On()

jQuery’s .bind() vs. .on()

Internally, .bind maps directly to .on in the current version of jQuery. (The same goes for .live.) So there is a tiny but practically insignificant performance hit if you use .bind instead.

However, .bind may be removed from future versions at any time. There is no reason to keep using .bind and every reason to prefer .on instead.

is jquery on() always better than bind()

From jQuery source code :

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

As you see, bind just calls on. There's NO reason to use bind. Never.

jquery use of bind vs on click

From the documentation of bind and click :

bind :

As of jQuery 1.7, the .on() method is the preferred method for
attaching event handlers to a document.

The source makes it clear there's no reason to use bind, as this function only calls the more flexible on function without even being shorter :

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

So I'd suggest, just like the jQuery team, to forget the old bind function, which is now useless. It's only for compatibility with older code that it's still here.

click :

This method is a shortcut for .on('click', handler)

This shortcut is of course less powerful and flexible than the on function and doesn't allow delegation but it lets you write a shorter and, arguably, slightly more readable, code when it applies. Opinions diverge on that point : some developers argue that it should be avoided as it is just a shortcut, and there's also the fact that you need to replace it with on as soon as you use delegation, so why not directly use on to be more consistent ?

What's the difference between jQuery.bind() and jQuery.on()?

.on() now offers a combination of .live(), .delegate() and .bind() all in one unified method. You can get the behavior of any of those three just by how you use the arguments to .on().

These pairs are functionally the same:

// events bound directly to the object they occur on
$('.button').on('click', fn);
$('.button').bind('click', fn);

// events intercepted after bubbling up to a common parent object
$('.container').on("click", '.button', fn);
$('.container').delegate('.button', "click", fn);

More info is described in a jQuery blog entry.

Before unifying these separate functions, jQuery had multiple different implementations. Now, .on() is the superset function and .bind(), .live() and .delegate() all just call .on() in their implementation so there is now only one implementation of the actual event handling. So, from that standpoint, it was also a code cleanup and streamlining issue. Similarly, .die(), .undelegate() and .unbind() just call .off() now rather than have separate implementations.

Note: .live() has been deprecated for all versions of jQuery because it's just a special case of intercepting all the bubbled events on the document object so it can be easily replaced with either .delegate() or .on() and when lots of events were all being handled on the document object, it could become a performance problem checking lots of selectors on every event. It's much more efficient to hook a delegated event like this to a common parent that is much closer to where the event occurs than put them all on the document object (thus why .live() is not good to use).

From the jQuery 1.7 source, you can see how all these functions just now call .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 );
},

live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},

delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
},

What's the difference between `on` and `live` or `bind`?

on() is an attempt to merge most of jQuery's event binding functions into one. This has the added bonus of tidying up the inefficiencies with live vs delegate. In future versions of jQuery, these methods will be removed and only on and one will be left.

Examples:

// Using live()
$(".mySelector").live("click", fn);

// Equivalent `on` (there isn't an exact equivalent, but with good reason)
$(document).on("click", ".mySelector", fn);
// Using bind()
$(".mySelector").bind("click", fn);

// Equivalent `on`
$(".mySelector").on("click", fn);
// Using delegate()
$(document.body).delegate(".mySelector", "click", fn);

// Equivalent `on`
$(document.body).on("click", ".mySelector", fn);

Internally, jQuery maps all these methods and shorthand event handler setters to the on() method, further indicating that you should ignore these methods from now on and just use on:

bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},

See https://github.com/jquery/jquery/blob/1.7/src/event.js#L965.

Best practice using BIND or ON functions in jQuery

The jQuery project is moving towards putting more and more functionality in fewer methods, instead of having separate methods for every separate thing.

The methods bind, live and delegate have all been replaced by the single method on, where you use parameters of different types to determine what the method does.

Comparison:

$(sel).bind(event, f);            =    $(sel).on(event, f);
$(sel).live(event, f); = $(document.body).on(event, sel, f);
$(sel).delegate(sel2, event, f) = $(sel).on(event, sel2, f);

If you are using live, you should replace that, as the usage of that method is a bit awkward. Also, the live method creates a delegate on the body element, and you should try to bind the delegate to a closer scope.

If you are using bind and delegate it's no panic to replace them with on right away. You can do that in new code, and in code that you edit anyway, but those methods are not about to go away in the nearest future.

Difference between jQuery `click`, `bind`, `live`, `delegate`, `trigger` and `on` functions (with an example)?

Before you read this, pull this list of events up in another page, the API itself is tremendously helpful, and all of what I'm discussing below is linked directly from this page.

First, .click(function) is literally a shortcut for .bind('click', function), they are equivalent. Use them when binding a handler directly to an element, like this:

$(document).click(function() {
alert("You clicked somewhere in the page, it bubbled to document");
});

If this element gets replaced or thrown away, this handler won't be there anymore. Also elements that weren't there when this code was run to attach the handler (e.g. the selector found it then) won't get the handler.

.live() and .delegate() are similarly related, .delegate() actually uses .live() internally, they both listen for events to bubble. This works for new and old elements, they bubble events the same way. You use these when your elements may change, e.g. adding new rows, list items, etc. If you don't have a parent/common ancestor that will stay in the page and not be replaced at any point, use .live(), like this:

$(".clickAlert").live('click', function() {
alert("A click happened");
});

If however you do have a parent element somewhere that isn't getting replaced (so its event handlers aren't going bye bye) you should handle it with .delegate(), like this:

$("#commonParent").delegate('.clickAlert', 'click', function() {
alert("A click happened, it was captured at #commonParent and this alert ran");
});

This works almost the same as .live(), but the event bubbles fewer times before being captured and the handlers executed. Another common use of both of these is say your class changes on an element, no longer matching the selector you originally used...with these methods the selector is evaluated at the time of the event, if it matches, the handler runs...so the element no longer matching the selector matters, it won't execute anymore. With .click() however, the event handler is bound right on the DOM element, the fact that it doesn't match whatever selector was used to find it is irrelevant...the event is bound and it's staying until that element is gone, or the handler is removed via .unbind().

Yet another common use for .live() and .delegate() is performance. If you're dealing with lots of elements, attaching a click handler directly to each element is expensive and time consuming. In these cases it's more economical to setup a single handler and let bubbling do the work, take a look at this question where it made a huge difference, it's a good example of the application.


Triggering - for the updated question

There are 2 main event-handler triggering functions available, they fall under the same "Event Handler Attachment" category in the API, these are .trigger() and .triggerHandler(). .trigger('eventName') has some shortcuts built-in for the common events, for example:

$().click(fn); //binds an event handler to the click event
$().click(); //fires all click event handlers for this element, in order bound

You can view a listing including these shortcuts here.

As for the difference, .trigger() triggers the event handler (but not the default action most of the time, e.g. placing the cursor at the right spot in a clicked <textarea>). It causes the event handlers to occur in the order they were bound (as the native event would), fires the native event actions, and bubbles up the DOM.

.triggerHandler() is usually for a different purpose, here you're just trying to fire the bound handler(s), it doesn't cause the native event to fire, e.g. submitting a form. It doesn't bubble up the DOM, and it's not chainable (it returns whatever the last-bound event handler for that event returns). For example if you wanted to trigger a focus event but not actually focus the object, you just want code you bound with .focus(fn) to run, this would do that, whereas .trigger() would do that as well as actually focus the element and bubble up.

Here is a real world example:

$("form").submit(); //actually calling `.trigger('submit');`

This would run any submit handlers, for example the jQuery validation plugin, then try to submit the <form>. However if you just wanted to validate, since it's hooked up via a submit event handler, but not submit the <form> afterwards, you could use .triggerHandler('submit'), like this:

$("form").triggerHandler('submit');

The plugin prevents the handler from submitting the form by bombing out if the validation check doesn't pass, but with this method we don't care what it does. Whether it aborted or not we're not trying to submit the form, we just wanted to trigger it to re-validate and do nothing else. (Disclaimer: This is a superfluous example since there's a .validate() method in the plugin, but it's a decent illustration of intent)

Jquery Difference B/w Jquery bind events

Have a look at the event delegation jQuery documentation

basically

$(document).on("click","#btn",callback);

will bind the click to the document DOM rather than the element directly which is useful when you are appending DOM elements to the window in which case the #btn selector will not exist yet.



Related Topics



Leave a reply



Submit