Skip to content

Instantly share code, notes, and snippets.

@brainopia
Created January 24, 2012 20:35
Show Gist options
  • Save brainopia/1672410 to your computer and use it in GitHub Desktop.
Save brainopia/1672410 to your computer and use it in GitHub Desktop.
class @SortableTable
constructor: (table, options) ->
@table = $(table).children('tbody')
@columnSelector = options.columnSelector || 'th'
@iconSelector = options.iconSelector
@rowMapper = options.rowMapper
@afterSort = options.afterSort
@enable()
getColumn: (element) ->
new Column $(element), @iconSelector
activeColumn: ->
@getColumn @table.find(@columnSelector).filter(".#{Column.activeClass}")
enable: ->
@table.on 'click', @columnSelector, @handleClick
handleClick: (event) =>
column = @getColumn event.currentTarget
if column.isActive()
column.reverse()
else
@activeColumn().deactivate()
column.activate()
@sort(column)
rateCell: (cell) ->
parseFloat $(cell).text().replace(/[$\u00a0]/g, '')
sort: (column) ->
columnCells = @table.find("td:nth-child(#{column.index()})")
direction = if column.isReversed() then -1 else 1
columnCells.sort (cell1, cell2) =>
direction * (@rateCell(cell2) - @rateCell(cell1))
rows = columnCells.map (index, cell) =>
row = $(cell).parent()
row = @rowMapper(row) if @rowMapper
$.makeArray(row)
@table.append rows
@?.afterSort()
class Column
@activeClass: 'active'
@reverseClass: 'reverse'
constructor: (@element, iconSelector) ->
@icon = iconSelector && @element.find(iconSelector) || @element
isActive: ->
@element.hasClass(@constructor.activeClass)
isReversed: ->
@icon.hasClass(@constructor.reverseClass)
reverse: ->
@icon.toggleClass(@constructor.reverseClass)
deactivate: ->
@element.removeClass(@constructor.activeClass)
@icon.removeClass(@constructor.reverseClass)
activate: ->
@element.addClass(@constructor.activeClass)
index: ->
@element.parent().children().index(@element) + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment