Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Columns can have custom sort functions

  • Loading branch information...
commit b83d9300841991fc68260b955d11d11436346678 1 parent 60ffb62
@kylefox authored
Showing with 20 additions and 18 deletions.
  1. +7 −1 index.html
  2. +13 −17 jquery.tablesort.js
View
8 index.html
@@ -25,7 +25,7 @@
<th>Name</th>
<th>Band</th>
<th>Date of Birth</th>
- <th>Age</th>
+ <th class="number">Age</th>
</tr>
</thead>
<tbody>
@@ -65,6 +65,12 @@
$(function() {
sort = $('table').tablesort().data('tablesort');
+
+ $('thead th.number').data('sortBy', function(th, td, sorter) {
+ console.log("sort by number!");
+ return parseInt(td.text(), 10);
+ });
+
});
</script>
View
30 jquery.tablesort.js
@@ -14,12 +14,19 @@ $(function() {
}
}
+ function sortValueForCell(th, td, sorter) {
+ if(th.data().sortBy) {
+ var sortBy = th.data().sortBy;
+ return (typeof sortBy === 'function') ? sortBy(th, td, sorter) : sortBy;
+ }
+ return td.text();
+ }
+
function SortableTable($el) {
var self = this;
this.$el = $el;
this.$el.find('thead th').bind('click.tablesort', function() {
- var time = self.sortBy($(this));
- debug("Sorted in " + time + 'ms');
+ self.sort($(this));
});
this.index = null;
this.direction = null;
@@ -27,14 +34,7 @@ $(function() {
SortableTable.prototype = {
- sortBy: function(th) {
- var self = this;
- return bm(function() {
- self.sort(th.index());
- });
- },
-
- sort: function(column) {
+ sort: function(th) {
var self = this,
table = this.$el,
rows = table.find('tbody tr'),
@@ -43,14 +43,14 @@ $(function() {
if(rows.length === 0)
return;
- this.index = column;
+ this.index = th.index();
this.direction = this.direction === 'asc' ? 'desc' : 'asc';
direction = this.direction == 'asc' ? 1 : -1;
debug("Sorting by " + this.index + ' ' + this.direction);
rows.sort(function(a, b) {
- a = self.sortValueForCell(self.cellToSort(a));
- b = self.sortValueForCell(self.cellToSort(b));
+ a = sortValueForCell(th, self.cellToSort(a), self);
+ b = sortValueForCell(th, self.cellToSort(b), self);
if(a > b) {
return 1 * direction;
} else if(a < b) {
@@ -68,10 +68,6 @@ $(function() {
cellToSort: function(row) {
return $($(row).find('td').get(this.index));
- },
-
- sortValueForCell: function(cell) {
- return cell.text();
}
};

0 comments on commit b83d930

Please sign in to comment.
Something went wrong with that request. Please try again.