Search code examples
knockout.jstablesorter

knockout tablesorter caching rows


I have been breaking my head with this issue for about 5-6 hours now.

I am using tablesorter in combination with knockoutjs. My problem is when using tablesorter, the rows are cached and when I try to remove rows, they never disappear. I have created a jsfiddle explaining the problem. You can see my instructions in the fiddle.

http://jsfiddle.net/a8jUj/29/

I have been seeing a lot of articles which talk about this kind of issues but they all say that we need to call a trigger update after a change to the table which I did but that didnt work for me.

 $("#list1").trigger("update");

Please let me know what I am doing wrong.

Thanks.


Solution

  • The problem is that .tablesorter plugin does not sort self.users array in your model, it sorts actual <tr> elements only. Your column sorter must call observableArray.sort method explicitly with customized comparer as argument:

    self.sortCol = function(colName, event) {
    
        // get sorting direction
        var th = event.target;
        th.sortDir = (th.sortDir == 'asc' ? 'desc' : 'asc');
    
        // array item comparator
        function comp(a, b){
            // get values to compare
            var av = a[colName](), bv = b[colName]();
            // compare using current direction
            if (th.sortDir == 'asc') {
                return av == bv ? 0 : av > bv ? 1 : -1;
            } else {
                return av == bv ? 0 : av < bv ? 1 : -1;
            }
        }
        // do sort
        self.users.sort(comp);
    }
    

    Working fiddle: http://jsfiddle.net/a8jUj/31/

    P.S. Just for example I've bound .sortCol() via function to gain access to event object. You can rewrite your model to store current sorting parameters in model properties.