Sortable Table
by zakkarygrahamm
HTML
<table>
<thead>
<tr data-bind="foreach: headers">
<th data-bind="click: $parent.sort, text: title"></th>
</tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td data-bind="text: firstName"></td>
<td data-bind="text: lastName"></td>
<td data-bind="text: age"></td>
</tr>
</tbody>
</table>
CSS
th
{
cursor:pointer;
}
JavaScript
var viewModel = function(){
var self = this;
self.people = ko.observableArray([
{firstName:'James',lastName:'Smith',age:38},
{firstName:'Susan',lastName:'Smith',age:36},
{firstName:'Jeremy',lastName:'Smith',age:10},
{firstName:'Megan',lastName:'Smith',age:7},
{firstName:'James',lastName:'Jones',age:40},
{firstName:'Martha',lastName:'Jones',age:36},
{firstName:'Peggy',lastName:'Jones',age:10}
]);
self.headers = [
{title:'First Name',sortPropertyName:'firstName', asc: true},
{title:'Last Name',sortPropertyName:'lastName', asc: true},
{title:'Age',sortPropertyName:'age', asc: true}
];
self.activeSort = self.headers[0]; //set the default sort
self.sort = function(header, event){
//if this header was just clicked a second time
if(self.activeSort === header) {
header.asc = !header.asc; //toggle the direction of the sort
} else {
self.activeSort = header; //first click, remember it
}
var prop = self.activeSort.sortPropertyName;
var ascSort = function(a,b){ return a[prop] < b[prop] ? -1 : a[prop] > b[prop] ? 1 : a[prop] == b[prop] ? 0 : 0; };
var descSort = function(a,b){ return a[prop] > b[prop] ? -1 : a[prop] < b[prop] ? 1 : a[prop] == b[prop] ? 0 : 0; };
var sortFunc = self.activeSort.asc ? ascSort : descSort;
self.people.sort(sortFunc);
};
}
ko.applyBindings(new viewModel());