Search code examples
ember.jsember-table

ember-table even odd color strip


I get stuck while adding even/odd color strips to table rows in ember-table.

Regular CSS selector :even :odd won't work because the lazy table will reusing existing limited number of row elements, so the first element in DOM may not be the first row on screen nor array of data.

Did anyone solve this issue before?


Solution

  • I found a way to do that.

    In Table class, rows property

    rows: Ember.computed(function() {
      var root = this.get('root');
      if (!root) {
        return Ember.A();
      }
      var rows = this.flattenTree(null, root, Ember.A());
      this.computeStyles(null, root);
    
      // start of modification
      // now each row has an 'isShowing' boolean flag
      // _.rest is underscore function to skip the first element
      // (in my case it is an empty TableRow instance)
      _.rest(rows).filterProperty('isShowing').forEach(function (row, i) {
        row.set('evenOdd', (i % 2 === 0) ? 'even' : 'odd');
      });
      // end of modification
    
      var maxGroupingLevel = Math.max.apply(rows.getEach('groupingLevel'));
      rows.forEach(function(row) {
        return row.computeRowStyle(maxGroupingLevel);
      });
      return rows;
    }).property('root'),
    

    In Row class computedRowStyle method

    computeRowStyle: function(maxLevels) {
      var level = this.getFormattingLevel(this.get('groupingLevel'), maxLevels);
      // start of modifications
      var evenOdd = this.get('evenOdd');
      this.set('rowStyle', 'ember-table-row-style-%@ ember-row-evenodd-%@'.fmt(level, evenOdd));
      // end of modifications
    },
    

    Whatever value set in rowStyle will be shown in row element class, so only need to add two more styles in CSS ember-row-evenodd-even and ember-row-evenodd-odd