Retrieve click() handler in jQuery for later use

Posted by Xiong Chiamiov on Stack Overflow See other posts from Stack Overflow or by Xiong Chiamiov
Published on 2010-04-13T04:42:58Z Indexed on 2010/04/13 4:52 UTC
Read the original article Hit count: 385

I'm using the jQuery tablesorter plugin to sort a table, which assigns .click() handlers to the <th>s in the table. Since my table has alternating colors for each column, I've built a simple fix_table_colors(identifier) function that does as it should when I call it manually using Firebug. I would like, however, to have that automatically called after a sort.

To do this, I decided to retrieve the .click() handler from the <th>s, and assign a new handler that simply calls the previous handler, followed by fix_table_colors().

(This SO question is similar, but uses standard onClick() attributes, which won't work here.)

From the accepted answer to this question, I have created the following code:

$(document).ready(function() {
    $("table.torrents").tablesorter({
        debug: true,
        headers: {
            1: { sorter: 'name' },
            2: { sorter: 'peers' },
            3: { sorter: 'filesize' },
            4: { sorter: 'filesize' },
            5: { sorter: 'filesize' },
            6: { sorter: 'ratio' }
        }
    });

    $('table.torrents thead th').each(function() {
        var th = $(this);
        var clickHandler = th.data('events').click[0];
        th.click(function() {
            clickHandler();
            fix_table_colors('table.torrents');
        });
    });
});

While this is conceptually correct, clickHandler doesn't appear to actually be a function, and so I cannot call it.

With a bit more digging in Firebug, I found that click[3] appears to hold the function I'm looking for (and click[10] my new one). I get an 'e is undefined' error on line 2 of tablesorter.min.js when using that, though.

Am I even going down the right path? I have a feeling that with what I've found so far, I can make this work, but it's going to be much uglier than I would expect it needs to be.

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about jquery-plugins