Skip to content

Instantly share code, notes, and snippets.

@tater9104
Created March 30, 2012 21:52
Show Gist options
  • Save tater9104/2255674 to your computer and use it in GitHub Desktop.
Save tater9104/2255674 to your computer and use it in GitHub Desktop.
Utilizing Knockout.JS & Tablesorter together.
// Using Knockout and Tablesorter is a little tricky due to the fact that
// knockout tends to have a slight delay in load (if you are making an ajax call)
// and that table sorter likes to cache its value. To make them work together,
// on need to pay attention to execution order...
//
// Credit: Steve Sanderson http://bit.ly/H1B2Jm
// When binding your table, be sure to use the postAction event on the data-bind
// attribute to call the tablesorter() update method on your view:
//
// <tbody data-bind="foreach: items, postAction: tablesorter()">
function SomeViewModel() {
var self = this;
self.items= ko.observableArray([]);
// Add the tablesorter update function as a member of this object.
// this will allow you to call update during the Knockout binding process.
self.tablesorter = function () {
setTimeout(function () {
// tablesorter will complain if you have empty rows in tbody.
if (self.items().length != 0) {
$(".tablesorter").trigger("update");
$(".tablesorter").trigger("sorton", [[[0, 0], [1, 0]]]);
}
}, 10);
}
};
var viewModel= new SomeViewModel();
$(document).ready(function () {
//tablesorter needs to be called first...
$(".tablesorter").tablesorter({ widgets: ['zebra'] });
ko.applyBindings(viewModel);
});
@doingweb
Copy link

For posterity: postAction is not some undocumented built-in binding. I just spent way too much time searching around for something telling me about its behavior and ended up just tracing through Knockout. Hopefully I can save you from the same fate.

When bindings are parsed, their values are all evaluated at once (see ko.bindingProvider.parseBindingsString and createBindingsStringEvaluator in the bindingProvider). Then, the handlers for those bindings are called, if they exist. If they don't exist (like postAction), they are silently ignored. So this code, as well as the code from Steve Sanderson's post and some other places, are simply exploiting this side effect and chose the same name for the nonexistent binding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment