Skip to content

Instantly share code, notes, and snippets.

@thejefflarson
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save thejefflarson/11195030 to your computer and use it in GitHub Desktop.

Select an option

Save thejefflarson/11195030 to your computer and use it in GitHub Desktop.

Revisions

  1. thejefflarson revised this gist Apr 22, 2014. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion Sorty.js
    Original file line number Diff line number Diff line change
    @@ -18,7 +18,7 @@
    return this.el;
    };

    var Sorty = window.Sorty = function(el, opts){
    var Sorty = window.Sorty = function(el){
    this.el = $(el);
    this.rows = $.map(this.el.find('tbody tr'), function(el){
    return new Row(el);
  2. thejefflarson revised this gist Apr 22, 2014. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion Sorty.js
    Original file line number Diff line number Diff line change
    @@ -36,7 +36,7 @@
    this.orders[by] = -1;
    }

    var that = this, order = this.orders[by], ret = [];
    var order = this.orders[by], ret = [];
    var sorted = this.rows.sort(function(a, b) {
    return (a.values[by] < b.values[by] ? 1 : -1) * order;
    });
  3. thejefflarson created this gist Apr 22, 2014.
    62 changes: 62 additions & 0 deletions Sorty.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,62 @@
    // 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, opts){
    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 that = this, 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");
    };
    })();