javascriptsortingkendo-uikendo-gridkendo-datasource

Custom Sort on Kendo Grid that can be Triggered Programmatically


I have a kendo grid and want certain rows to stay pinned at the top of the grid after sorting. I can achieve this by specifying a custom sort on every column. For example:

<script>
    var ds = new kendo.data.DataSource({
        data: [
            { name: "Jane Doe", age: 30, height: 170, pinToTop: false },
            { name: "John Doe", age: 33, height: 180, pinToTop: false },
            { name: "Sam Doe", age: 28, height: 185, pinToTop: true },
            { name: "Alex Doe", age: 24, height: 170, pinToTop: false },
            { name: "Amanda Doe", age: 25, height: 165, pinToTop: true }
        ]
    });

    $('#grid').kendoGrid({
        dataSource: ds,
        sortable: {mode: 'single', allowUnsort: false},
        columns: [{
            field: "name",
            title: "Name",
            sortable: {
                compare: function (a, b, desc) {
                    if (a.pinToTop && !b.pinToTop) return (desc ? 1 : -1);
                    if (b.pinToTop && !a.pinToTop) return (desc ? -1 : 1);
                    if (a.name > b.name) return 1;
                    else return -1;
                }
            }
        }
        //Other columns would go here
        ]
    });
</script>

This works fine when the grid is sorted by the user clicking on a column header. However, if I want to sort the grid using Javascript code, like so:

$('#grid').data('kendoGrid').dataSource.sort({field: 'age', dir: 'asc'});

The pinToTop field is ignored. This is because the sort is performed on the DataSource, but the custom sort logic is part of the grid.

JSFiddle Example

I need to either:

Or:


Solution

  • It wasn't quite what I wanted, but I was able to solve this issue by sorting on multiple fields and including the pinToTop field first:

    $('#grid').data('kendoGrid').dataSource.sort([{field: 'pinToTop', dir: 'desc'},{field: 'age', dir: 'asc'}]);