KendoGrid move the grid's row up and down

kendo.ui 2014.2.903

by Alger Chen

HTML

<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.2.903/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.2.903/styles/kendo.default.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.2.903/js/kendo.all.min.js"></script>
<div id="grid"></div>

JavaScript

var data = [
    { id: 1, text: "text 1", position: 0 },
    { id: 2, text: "text 2", position: 1 },
    { id: 3, text: "text 3", position: 2 }
]
var dataSource = new kendo.data.DataSource({
        data: data,        
        schema: {
            model: {
                id: "id",
                fields: {
                    id: { type: "number" },
                    text: { type: "string" },
                    position: { type: "number" }
                }
            }
        }
    });

var grid = $("#grid").kendoGrid({
    dataSource: dataSource,  
    scrollable: false,    
    columns: ["id", "text", "position",{
        command: [
                    { text: "Up", click: moveUp },
                    { text: "Down", click: moveDown }
                ], 
        title: "command"
    }]            
}).data("kendoGrid");


    function moveUp(e) {
        e.preventDefault();
        var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
        moveRow(this, dataItem, -1);
    }

    function moveDown(e) {
        e.preventDefault();
        var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
        moveRow(this, dataItem, 1);
    }
    function swap(a,b,propertyName){
      var temp=a[propertyName];
      a[propertyName]=b[propertyName];
      b[propertyName]=temp;
    }
    function moveRow(grid, dataItem,direction) {
        var record = dataItem;
        if (!record) {
            return;
        }
        var newIndex = index = grid.dataSource.indexOf(record);
        direction < 0?newIndex--:newIndex++;
        if (newIndex < 0 || newIndex >= grid.dataSource.total()) {
            return;
        }
        swap(grid.dataSource._data[newIndex],grid.dataSource._data[index],'position');
        grid.dataSource.remove(record);
        grid.dataSource.insert(newIndex, record);
                
    }