Search code examples
javascriptknockout.jskogrid

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:

enter image description here


Solution

  • 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:

    enter image description here