0

I am building an app using MarionetteJS with Material Lite.

I have an issue when sorting the collection in a datatable component. ListView js is a Marionette.CompositeView instance

Here is the code:

listView.js

events: {
  'click .sort': 'onSort'
},
onSort: function(e) {
  e.preventDefault();
  var dataTable = this.$('.mdl-data-table');
  var element = this.$(e.currentTarget);
  this.collection.sortField = element.data('field');
  this.collection.sortDir = element.hasClass('mdl-data-table__header--sorted-descending') ? -1 : 1;

  //sort collection
  this.collection.sort();
}

schema

comparator: function(m1) {
  var field = this.sortField;
  var dir = this.sortDir;
  return (dir == -1) ? -m1.get(field) : m1.get(field);
}

template.html

<table class="mdl-data-table mdl-js-data-table mdl-data-table--selectable">
    <thead>
        <tr>
            <th class="mdl-data-table__cell--non-numeric">Category</th>
            <th class="mdl-data-table__cell--non-numeric mdl-data-table__header--sorted-ascending sort" data-field="entry_date">Date</th>
            <th class="mdl-data-table__cell mdl-data-table__header--sorted-ascending sort" data-field="amount">Amount</th>
            <th class="mdl-data-table__cell--non-numeric">Kind</th>
            <th class="mdl-data-table__cell"></th>
        </tr>
    </thead>
    <tbody class="records-items"></tbody>
</table>

so when the collection is sorted, i have to change the classes in the element like this:

//update UI
  if(this.collection.sortDir == 1) {
    element.addClass('mdl-data-table__header--sorted-descending');
    element.removeClass('mdl-data-table__header--sorted-ascending');
    this.collection.sortDir = -1;
  } else {
    if(this.collection.sortDir == -1) {
      element.addClass('mdl-data-table__header--sorted-ascending');
      element.removeClass('mdl-data-table__header--sorted-descending');
      this.collection.sortDir = 1;
    }
  }

but when call onRender, which calls component.UpgradeDom() internally the changes are not applied to the element (th), because the datatable is rendered from scratch..

listView.js

onRender: function() {
  componentHandler.upgradeDom();
}

my question is, when to update the element css classes?

thanks in advance :)

rvpanoz
  • 75
  • 2
  • 9

1 Answers1

0

Try something like:

templateHelpers: function() {
  return {
    sortDir: this.collection.sortDir,
    sortAmount: this.collection.sortField === 'amount',
    sortEntryDate: this.collection.sortField === 'entry_date'
  };
}

and then use those in your template to render the class based on your stored state.

Personally I would also not use hasClass use the data you've stored to determine what class to display.

Paul Falgout
  • 121
  • 4