Last Updated: February 25, 2016
·
2.951K
· spiegela

Enable dynamic sorting in Ember-Table

Ember-Table is a great way to display your tabular data in ember with some really nice features like draggable columns, lazy loading, etc. I'm not sure if this will work great with lazy data sources, but if you can use arrangedContent in your controller, you can add column-clicking greatness with just a few functions/overloads:

App.VeryOwnTableController = Ember.Table.TableController.extend Ember.SortableMixin,
  hasHeader: yes
  sortAscending: yes
  sortProperties: ['firstName']

  sortByColumn: (column)->
    # Toggle sort order for second press on same column
    if Ember.isEqual (column.get 'contentPath'), (@get 'sortProperties')[0]
      @toggleProperty 'sortAscending'
    else
      @set 'sortProperties', [column.get 'contentPath']
    @sort()

  sort: ->
    #Make sure we re-render on a sort order change
    @propertyWillChange 'content'
    (@get 'arrangedContent').sort()
    @propertyDidChange 'content'

  bodyContent: Ember.computed ->
    # overload bodyContent to bind to arrangedContent rather than content
    Ember.Table.RowArrayProxy.create
      tableRowClass: Ember.Table.Row
      content: @get 'arrangedContent'
  .property 'content'

  _contentWillChange: Ember.beforeObserver ->
    # Must overload this, or SortableMixin upchucks
    console.log "do nothing here"

   columns: # Define as usual -- use contentPath for this to work as advertised