Last active
August 29, 2015 14:00
-
-
Save thejefflarson/11195030 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// usage: var mytable = new Sorty(table); | |
(function(){ | |
var Row = function(el) { | |
this.values = $.map($(el).find('td'), function(e) { | |
var el = $(e); | |
var attr = el.attr('data-sort'); | |
return attr ? parseFloat(attr) : el.text(); | |
}); | |
this.el = $(el); | |
}; | |
Row.prototype.value = function(i){ | |
return this.values[i]; | |
}; | |
Row.prototype.get = function(){ | |
return this.el; | |
}; | |
var Sorty = window.Sorty = function(el){ | |
this.el = $(el); | |
this.rows = $.map(this.el.find('tbody tr'), function(el){ | |
return new Row(el); | |
}); | |
this.orders = []; | |
this.body = this.el.find('tbody'); | |
this.headers = this.el.find('thead tr:last-child th'); | |
this.headers.on('click', _.bind(this.click, this)); | |
}; | |
Sorty.prototype.sort = function(by){ | |
if(this.orders[by]) { | |
this.orders[by] *= -1; | |
} else { | |
this.orders[by] = -1; | |
} | |
var order = this.orders[by], ret = []; | |
var sorted = this.rows.sort(function(a, b) { | |
return (a.values[by] < b.values[by] ? 1 : -1) * order; | |
}); | |
var l = sorted.length; | |
for(var i = 0; i < l; i++) | |
ret.push(this.rows[i].get()); | |
return ret; | |
}; | |
Sorty.prototype.click = function(e){ | |
var cur = $(e.currentTarget); | |
var idx = this.headers.index(cur); | |
this.body.html(this.sort(idx)); | |
this.headers.removeClass("sortyUp sortyDown"); | |
if (this.orders[idx] == -1) | |
cur.addClass("sortyUp"); | |
else | |
cur.addClass("sortyDown"); | |
}; | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment