Josh,

>I have a table that has 1,000 rows and I'm trying to bind a function
>to the click event of each row.  This can be quite slow the way I'm
>currently doing it.  Here is an example my my current process:
>
>       this.find(settings.selector).click(function(){selectRow(this);});
>
>       function selectRow(row){
>               if(row && !jQuery(row).is("."+settings.selectedClass)){
>                       table.find(settings.selector
>+"."+settings.selectedClass).removeClass(settings.selectedClass);
>                       jQuery(row).addClass(settings.selectedClass);
>                       if(settings.selectFunction)
>                               settings.selectFunction(row);
>               }
>       }
>
>settings.selector = "tbody tr",  this=table = $("#test"),
>settings.selectedClass="selected", settings.selectFunction =null
>
>This can take 8 seconds or more and will cause IE to display the long
>running script dialog on my test machine.
>
>So, now my question.  Since I need to do an action on the click event
>of each row, is it best to bind a function to each row separately, or
>is there someway to bind a function to the click event of tbody and
>then figure out the row somehow?
>
>Also, does anybody see anything stupid with the code above that would
>invoke such a slowdown?

It's definitely faster to bind the click behavior to the entire table and
use the event object passed to your callback to determine whether or not to
perform the behavior.

// bind an onclick event to the entire table
$("#table").bind(
        "click",
        function (e){
                alert(e.target);
        }
);

The above function will tell you which element got click on in your table.
The one "gotcha" is you need to do some parsing to actually find the parent
element you want. I've used something like:

/*
        if the current element is not the one we wants, search the 
        parent nodes for a match
*/
function findTarget(el, selector){
        var jel = $(el);
        return (jel.is(selector)) ? jel : jel.parents(selector);
}

Now you can use something like:

// bind an onclick event to the entire table
$("#table").bind(
        "click",
        function (e){
                // alert the parent <tr /> element
                alert(findTarget(e.target, "tr"));
        }
);

-Dan

PS - The findTarget could easily be re-written into a jQuery plug-in.

Reply via email to