How to work with Jquery Table Sorter with knockout

半世苍凉 提交于 2019-11-30 14:21:06

Here is an example: http://jsfiddle.net/jearles/RGsEH/

NOTE: The JS and CSS file dependencies are brought in under Managed Resources.

HTML

<table data-bind="sortTable: true">
  <thead>
    <tr>
      <th>Type</th>
      <th>Title</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: course">
   <tr>
      <td data-bind="text: type"></td>
      <td data-bind="text: title"></td>
    </tr> 
  </tbody>
 </table>

JS

function Course(type, title) {
    this.type = type;
    this.title = title;
}

var ViewModel = function() {
    this.course = ko.observableArray([
        new Course("type", "course1"),
        new Course("another_type", "course2"),
        new Course("second_type", "course5"),
        new Course("third_type", "course4"),
        new Course("fourth_type", "course3")        
    ]);
}

ko.bindingHandlers.sortTable = {
    init: function(element, valueAccessor) {
        setTimeout( function() {
            $(element).addClass('tablesorter');
            $(element).tablesorter({widgets: ['zebra']});
        }, 0);
    }
};

ko.applyBindings(new ViewModel());

The above solution by @john Earles works on pre defined data tables but when we are adding dynamic data to tables, it kinda breaks.

please check this : http://jsfiddle.net/vkctata/vdcox07c/1/

function Course(type, title) {
      this.type = type;
      this.title = title;
    }
    var ViewModel = function() {
      this.addNewItem = function() {
        this.course.push(new Course("nth_type", "course33"));
        return false;
      }
      this.course = ko.observableArray([
        new Course("type", "course1"),
        new Course("another_type", "course2"),
        new Course("second_type", "course5"),
        new Course("third_type", "course4"),
        new Course("fourth_type", "course3")
      ]);
    }

    ko.bindingHandlers.sortTable = {
      init: function(element, valueAccessor) {
        setTimeout(function() {
          $(element).addClass('tablesorter');
          $(element).tablesorter({
            widgets: ['zebra']
          });
        }, 0);
      }
    };

    ko.applyBindings(new ViewModel());

we found a way to create nearly generic sorting, please follow this link knockout sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!