Jquery event binding – jquery live api

Hi All,

Recently i faced an issue while developing a Asp.Net MVC3.0 application. On a link click i was trying to add new html to the existing DOM. For example on click of a link i was adding some new html tags to the existent DOM. Here is the code i wrote to make an ajax call on link click.


$(".editanchor").click(function () {

$.ajax({
// set the attributes and call an action method
});
});

It all worked fine but strangely when i click the link next time nothing happens. Then i realized the mistake i made while binding the click event to a handler.

As per jquery documentation Live() method should be used to bind the event to a callback if we are modifying the DOM structure during our page reload (partial or full) so that it would retain the binding next time you click the link.

Live(event, handler) : Attaches an event handler for all elements which match the current selector, now and in the future.

so the correct way to bind an event to a handler in such condition would be

$(".editanchor").live('click', function () {

$.ajax({
// set the attributes and call an action method
});
});

There are few performance considerations we should be aware of

  • Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled.
  • jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be time-consuming on large documents.

EDIT: Here is the updated comparison of various flavors of binding an event.

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

I hope it helps.  

Advertisements

About saxenapraveen

I work with Microsoft and have 12 years of experience in developing,designing and leading reliable and scalable solutions for cloud and device ready businesses.

Posted on November 28, 2011, in Javascript, Jquery and tagged , , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: