Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utilizing jquery.tablesorter with a jquery.tmpl generated table

I have a table that is dynamically generated wit jquery.tmpl from a KnockoutJS observableArray viewModel. After the initial binding, I also apply tablesorter to the table id to get sorting.

As I would "expect" whenever an item is removed (or added to) the viewModel, the table updates, but after the update tablesorter is not functional unless I again call $("#id").tablesorter();.

Is there a best practice here for using both jQuery.tablesorter with KnockoutJS? Is there a better plugin to use here? Obviously what I'm doing works, but I wonder if I'm missing something simple that would be more efficient.

like image 737
TodK Avatar asked May 30 '26 22:05

TodK


1 Answers

Rather than call $("#id").tablesorter() each time, you can call $("#id").trigger("update").

This seems to be the preferred way to let tablesorter know that there is new data to consider based on the docs.

If you wanted to get a little fancier with it, you could create a custom binding for your table that gets called any time that your observableArray changes.

Would look like this:

ko.bindingHandlers.triggerUpdate = {
    update: function (element, valueAccessor) {
        ko.utils.unwrapObservable(valueAccessor()); //need to just access the observable to create the subscription
        $(element).trigger("update");
    }
}

Then, you would put this on your table like:

<table id="mytable" data-bind="triggerUpdate: items">
like image 135
RP Niemeyer Avatar answered Jun 02 '26 21:06

RP Niemeyer