0

I am using Backgrid. I found that one of my columns has 'undefined' value. Backgrid sorting doesn't work correctly when there is undefined in the column. I looked into the source code.

onClick: function (e) { e.preventDefault();

var columnName = this.column.get("name");

if (this.column.get("sortable")) {
  if (this.direction() === "ascending") {
    this.sort(columnName, "descending", function (left, right) {
      var leftVal = left.get(columnName);
      var rightVal = right.get(columnName);
      if (leftVal === rightVal) {
        return 0;
      }
      else if (leftVal > rightVal) { return -1; }
      return 1;
    });
  }
  else if (this.direction() === "descending") {
    this.sort(columnName, null);
  }
  else {
    this.sort(columnName, "ascending", function (left, right) {
      var leftVal = left.get(columnName);
      var rightVal = right.get(columnName);
      if (leftVal === rightVal) {
        return 0;
      }
      else if (leftVal < rightVal) { return -1; }
      return 1;
    });
  }
}

},

I changed the code to the following and sorting works correctly (assume undefined is less than any value):

onClick: function (e) { e.preventDefault();

var columnName = this.column.get("name");

if (this.column.get("sortable")) {
  if (this.direction() === "ascending") {
    this.sort(columnName, "descending", function (left, right) {
      var leftVal = left.get(columnName);
      var rightVal = right.get(columnName);
      if (leftVal === undefined && rightVal != undefined) {
        return 1;
      }
      if (leftVal != undefined && rightVal === undefined) {
        return -1;
      }
      if (leftVal === rightVal) {
        return 0;
      }
      else if (leftVal > rightVal) { return -1; }
      return 1;
    });
  }
  else if (this.direction() === "descending") {
    this.sort(columnName, null);
  }
  else {
    this.sort(columnName, "ascending", function (left, right) {
      var leftVal = left.get(columnName);
      var rightVal = right.get(columnName);
      if (leftVal === undefined && rightVal != undefined) {
        return -1;
      }
      if (leftVal != undefined && rightVal === undefined) {
        return 1;
      }
      if (leftVal === rightVal) {
        return 0;
      }
      else if (leftVal < rightVal) { return -1; }
      return 1;
    });
  }
}

},

Is there any other way to deal with undefined value when sorting? Thanks!

curious
  • 21
  • 1

1 Answers1

0

Actually, I upgraded my backgrid to latest 0.3.5 which supports sortValue property for Backgrid.Column: http://wyuenho.github.io/backgrid/api/index.html#!/api/Backgrid.Column-cfg-defaults. I can define a function to return an empty string for undefine column value to make the sorting work correctly. That will solve my problem.

curious
  • 21
  • 1