In case you missed it, you can find the announcement here. Apart from the improved delegate performance (which turned out to be a wonderfully simple solution!) – the nicest feature IMO is the standardized way to bind events. The new .on() and .off() methods handle the new method of event binding. In a nutshell, we don’t have to worry about different methods such as .live(), .bind() and .delegate(). We also don’t have to worry about the event specific methods like .click(). We also don’t have to worry about the .unbind() method either. The simplified .on() and .off() methods consolidate these disparate methods into single, simplified, shortened and consolidated methods. Because of the improved performance with delegates, these methods are recipients of those improvements, assuming of course that a delegate is what will be manifested.
As to the .on method, the one are that requires special attention is the optional selector argument. To explain, let’s assume you have an element that has child elements and you wish to bind a click handler. I will use the example provided in the jquery documentation.
//in this example, a click handler will be attached to every table row. $("#dataTable tbody tr").on("click", function(event){ alert($(this).text()); });
The preceeding example could be quite expensive if you have a lot of rows. Note the following example which uses the optional selector argument:
//in this example, the bound element is the tbody, not the tr's under the tbody. //the second argument in the .on call is used, in this case, we pass the "tr" selector. $("#dataTable tbody").on("click","tr", function(event){ alert($(this).text()); });
The difference between these two examples may seem semantic. The difference is anything but. In the second example, the handler is attached to one element – the tbody. The event is then delegated to the tr elements – which is directly beneath the tbody. Per the jQuery documentation, when you delegate events, be sure to define them as close in proximity to the child objects that will actually be used to fire the events. Otherwise, jQuery has to work harder to traverse through the object hierarchy.
Finally, if you want an event that runs one time only and then detaches itself, check out the new .one() method. How many times have you defined an action the user can only do one time. All of that code that you wrote to manually unbind the event is no longer necessary thanks to the new .one() method!
Pingback: The Morning Brew - Chris Alcock » The Morning Brew #975