Increasing Event Binding Performance using Jquery Delegate

Today I was presented with a problem when binding click events to action icons. You know the scenario; you have a table with a list of data and one of the columns has icons/links like “edit”, “new”, “view”, “delete” etc. This is how I’m using the jQuery to bind the click event to the links like so.

$("a.action").click(function() {
    // perform tasks
});

This worked great, however when the list grew to 50 or more items, IE (yes i know) started complaining that the script is running too long. Now at the moment I have 7 actions multiplied by 50 items in the list which means it was looping 350 times. It shouldn’t be that bad but before IE9 JS performance is woeful.

To fix this issue, I needed to reduce the amount of event bindings. This is where jQuery.delegate() comes in. The syntax is a little different but its pretty easy to understand.

$("#listtable").delegate("a.action", "click", function() {
    // perform tasks
});

The selector in this case is the table where the links are contained within (children). The first parameter is the filter for the link that needs to be clicked. The second parameter is the event name. Custom events can be used here. And the third parameter is the callback function. So its pretty similar, however instead of creating 50 events, one for each row, I’m binding the event to the surrounding table element and then using the fact that the events bubble up through parent elements to catch the appropriate event.

IE happy, Adam happy!

Advertisements
This entry was posted in .NET and tagged , , . Bookmark the permalink.

3 Responses to Increasing Event Binding Performance using Jquery Delegate

  1. Gareth Elms says:

    Ah I didn’t realise jQuery had it’s own delegate() function, I’ve been doing the inner selector condition myself on the parent click event. Works the same, but I’ll use delegate() from now on

  2. Shakir says:

    Hi Schotime,
    It all make sense to me, but how can you cover 7 different actions into one delegate function unless you doing the same thing with 7 actions (like, new, edit, delete, view etc) or using switch/cases or if/else to kick the particular functionality in.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s