【问题标题】:Sorting custom (currency) formatted column in backgrid在 backgrid 中对自定义(货币)格式的列进行排序
【发布时间】:2020-05-15 10:05:22
【问题描述】:

我正在使用 Backgridjs 将数据从 json 对象显示到表。我目前正在使用格式化程序将字符串数字格式化为货币。一旦我这样做了,排序就不再正常工作,因为它排序为字符串而不是数字。如何在格式化我的列后启用 backgrid 排序?

Backgrid 支持数字、int、date/momentjs。找不到货币的扩展名

这是我的格式化程序类

formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
    fromRaw: function(rawData) {
      var re = /\-/;
      if (rawData === "" || rawData == null) {
        return "";
      } else if (rawData.match(re)) {
        return "-" + accounting.formatMoney(rawData.substr(1));
      } else {
        return accounting.formatMoney(rawData);
      }
    },
    toRaw: function(formattedData) {
      return formattedData;
    }


  }),

这是我的网格

var grid = new Backgrid.Grid({
collection: collection,
columns: [
{
  name: "cost",
  label: "Cost",
  cell: "number",
  formatter: currencyFormater 
  sortable: true
},
{
  name: "type",
  label: "Type",
  cell: Backgrid.NumberCell,
  sortable: true
}
]});

数据示例:

{ id: 1, cost: "150", type: 3 },
{ id: 2, cost: "12516.30", type: 2 },
{ id: 3, cost: "21400.85", type: 1 },
{ id: 4, cost: "146558.50", type: 1 },
{ id: 5, cost: "139982.75", type: 1 }

【问题讨论】:

  • 您是否考虑过将值保留为数字并使用 css 伪元素在其旁边简单地显示货币符号?
  • 嗨@TJ,那太好了。但是我将数据作为字符串获取,问题在于它们不会被格式化的点(数字的一部分)

标签: javascript backbone.js backgrid


【解决方案1】:

我最终使用 sortValue 来根据值进行特定的排序。就我而言,我将 parseFloat 与字符串值一起使用。

var grid = new Backgrid.Grid({
collection: collection,
columns: [
 {
   name: "cost",
   label: "Cost",
   cell: "number",
   sortValue: function(model) {
     return parseFloat(model.get("cost"));
 },
 formatter: currencyFormater 
 sortable: true
 },
 …
]});

【讨论】:

    猜你喜欢
    • 2020-10-20
    • 2016-01-07
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多