使用未定义的值进行Backgrid排序

时间:2014-01-31 19:01:52

标签: backgrid

我正在使用Backgrid。我发现我的一个列有'undefined'值。当列中未定义时,Backgrid排序无法正常工作。我查看了源代码。

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;
    });
  }
}

},

我将代码更改为以下内容并且排序正常工作(假设undefined小于任何值):

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;
    });
  }
}

},

排序时还有其他方法可以处理未定义的值吗?谢谢!

1 个答案:

答案 0 :(得分:0)

实际上,我将我的backgrid升级到最新的0.3.5,它支持Backgrid.Column的sortValue属性: http://wyuenho.github.io/backgrid/api/index.html#!/api/Backgrid.Column-cfg-defaults。我可以定义一个函数来为undefine列值返回一个空字符串,以使排序正常工作。这将解决我的问题。