简体   繁体   中英

KoGrid: Default sorting not working

As part of koGrid 2.1.1 I was not able to make the default sorting to work, meaning that if you want your grid to be sorted by a specific column/direction you won't get the expected behavior. Default sorting in koGrid is achieved by sortInfo while configuring the gridOptions for the very first time.

I have created an example using jsFiddle which demonstrates this issue. You can notice that the list is not sorted by name, even that I've specified the sortInfo to do so.

1. Initializing koGrid with sort info:

        this.gridOptions = {
            data: self.myData,
            ...
            sortInfo: ko.observable({
                column: { "field": "name" },
                "direction": "asc" 
            })
            ...
        };

2. Notice the list is not sorted, neither the arrow is showing up:

在此输入图像描述

I changed koGrid 2.2.1 debug js to use the sortInfo, if specified. Basically, I made two changes as follows:

1. Created a function which returns column by field into the Grid object:

window.kg.Grid = function (options) {
...
self.columnByField = function (field) {
        if(field) {
           var column;
           $.each(self.columns(), function (i, c) {
              if(field == c.field) {
                 column = c;
                 return false;
              }
           });
           return column;
        }
    }
...
}

2. Changed Grid object init method to look for sortInfo and sort the column:

window.kg.Grid = function (options) {
...
self.init = function () {
  ...
   self.buildColumns();
   var sortingProperties = self.sortInfo.peek();
   if(sortingProperties) {
      var col = self.columnByField(sortingProperties.column.field);
      if(col) {
         col.sortDirection(sortingProperties.direction === ASC ? DESC : ASC);
         col.sort();
      }

   }
  ...
}
...
}

By doing this the default sorting problem is solved. I have created a fork project on GitHub and added the new debug js file there.

Now when you load the grid for the very first time the sorting works as the below image shows:

在此输入图像描述

add function for gridOption sortInfo like below

 ....
    sortInfo: this.sortDetails;
  }

Define function sortDetails like below

this.sortDetails.subscribe(function (data) {
        this.sortData.sort(function (left, right) {
            return left == right ? 0 : (left < right ? -1 : 1);
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM