Tag Archives: IE
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!