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.
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With