Search code examples
javascriptbackbone.jsbackgrid

Sorting custom (currency) formatted column in backgrid


I'm using Backgridjs to display data from json object to table. I'm currently using a formatter to format string-numbers into currency. Once I did that the sorting no longer work properly as it sorting as a string rather than number. How can I enable sorting with backgrid after formatting my column ?

Backgrid support numbers, int, date/momentjs. Couldn't find extension for currency

this is my formatter class

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


  }),

And this is my grid

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

Example of data:

{ 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 }

Solution

  • I ended up using sortValue to do specific sorting base on value. In my case I used parseFloat with the string value.

    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
     },
     …
    ]});