Recently, I helped a developer with the JQuery TableSorter plugin where
he needed to run some code whenever the TableSorter finished sorting.
The plugin didn’t provide any callbacks in its configuration which
seemed odd, as this is normal practice with any JQuery plugin.
After digging through the plugin source code, I noticed it was using JQuery’s “trigger” method which dispatched a built-in or custom event. From there, the solution was simple. When initializing theTableSorter plugin, we used the “bind” method to listen for any event
bubbled up from within the plugin. In this case, we listened for the “SortEnd” event. An example can be seen below:
$("table.sortable")
.tablesorter()
.bind("sortEnd", function(){
// fired when sorting has finished
});
I had used the “trigger” method in an earlier project but never
seen it used before with a JQuery plugin. We can expect to see two
standards now on how to tap into a plugin event– one using callbacks, and
the other using events. If you run into a plugin that doesn’t give the
option to pass in a callback, be on the look out for a custom event
trigger!
Norman said:
Thank you for the information, I was really looking badly for a way to callback function after table sorting.
jyoseph said:
Genius dude, thanks for posting this. Works like a charm!
Marcusklaas said:
Awesome. Exactly what I needed. Indeed this is odd. I freaking love callback functionality and it’s a shame tablesorter doesn’t have any by default.
Marcusklaas said:
I use it for restriping (giving the odd and even rows distinct colors) after I sort, by the way.
Rich said:
For easy striping and automatic restriping without code, try out css pseudo selector nth-child….
.someclass tr:nth-child(even) {
background-color:grey;
}
I’m just trying to work out the relative merits of explicit callbacks and event triggers.
Which is best if I am writing my own jQuery plugin? My plugin is a custom control that has an intrinsic value that can be changed by user interaction. A “change” event feels right but how does this compare passing in an “onChange” callback?
- Is event handling asynch?
- How are events routed
- Are the any clever things like de-duping?
Any pointers welcomed!