JSFiddle - React, Tailwind, and code Playground

by kougiland

HTML

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="dept_table">
  <thead>
      <tr data-bind="click: sortFunction">
          <th id='id'>Id</th>
          <th id='name'>Name</th>
          <th id='description'>Description</th>
      </tr>
  </thead>

  <tbody data-bind="foreach: deptList">
      <tr>
              <td><span data-bind="text: id" /></td>
              <td><span data-bind="text: name" /></td>
              <td><span data-bind="text: description" /></td>
      </tr>    
  </tbody>
</table>

JavaScript

// deptlist data
var mylist = [
            {id:1, name:"Dept 1", description: "D1"},
            {id:2, name:"Dept 2", description: "D6"},
            {id:3, name:"Dept 3", description: "D3"},
            {id:4, name:"Dept 4", description: "D4"}];

// Deptlist-item Viewmodel
var Dept = function (data) {
  var self = this;

  for(var key in data){
    // this is the lazy approach usually you should only use observables where they are needed
    if(data.hasOwnProperty(key))this[key] = ko.observable(data[key]);
  }
};

// Deptlist Viewmodel
var Deptlist = function(table_data){
  var self = this;

  this.deptList = ko.observableArray([]);
  this.sortColumn = ko.observable("id");
  this.isSortAsc = ko.observable(true);

  for(var i = 0;i < table_data.length;i++){
    if(table_data.hasOwnProperty(i))this.deptList.push(new Dept(table_data[i]));
  }

  this.sortFunction = function(data,event){
    if(self.sortColumn() === event.target.id)
        self.isSortAsc(!self.isSortAsc());
    else
    {
        self.sortColumn(event.target.id);
        self.isSortAsc(true);
    }

    self.deptList.sort(function (a, b) {
       		if(a[self.sortColumn()]() < b[self.sortColumn()]())return !self.isSortAsc();
       		else return self.isSortAsc();
    });
  }
};

var deptList = new Deptlist(mylist);

ko.applyBindings(deptList,$('.dept_table')[0]);