Monday, July 1, 2013

How to migrate from live() method in jQuery 1.9?

As jQuery documentation says it here, the famous live() method has been completely removed in jQuery 1.9, so you have to migrate from it, anyhow.

It is actually quiet simple. The jQuery Library has introduced a method called on() which is even more complete in what live() method was doing. The following is its signature:

.on( events [, selector ] [, data ], handler(eventObject) )

where events is of type String  and it is one or more space-separated event types and optional namespaces, such as "click" or "change", selector is also of type String and it is the selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. Data can be of any type and it is passed to the handler in when an event is triggered, and lastly, handler is of type Function (to execute when the event is triggered).

There exist a rough formula to change your methods from live() to use on(), instead. Have a look at my example:
// This is the old live() method
$("#element-id").live('change', function(){ 
  // Event handler code goes here ...

//This is its equivalent in jQuery 1.9
$(document).on('change', "#element-id", function(){
  // Event handler code goes here ...
Were you able to find the formula? It is quiet easy: Change the place of first argument of live method to the third one in on(). Add the root DOM element to the first parameter of on() method and keep the event type. That's it!

No comments:

Post a Comment