Grid Preserve Group Collapse

http://stackoverflow.com/questions/13953278/telerik-kendo-ui-grid-grouping-and-sorting-survive-grid-refresh-but-collapsed#13953278

by whoamiwho

HTML

<script src="http://cdn.kendostatic.com/2012.3.1114/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.default.min.css">
<script src="http://demos.kendoui.com/content/shared/js/people.js"></script>
<ol><li>Group by City</li><li>Collapse Boston</li><li>Click Refresh Button</li></ol>
<button id="refresh">Refresh</button>
<div id="grid" style="height: 380px"></div>

JavaScript

var _getCollapsedUids = function () {
    var collapsedUids = [];
    $("#grid .k-grouping-row span[data-uid]")
        .each(function(idx, item) {
            if($(item)
               .closest(".k-grouping-row")
               .children("td:first")
               .attr("aria-expanded") === "false") {
                collapsedUids.push($(item).data("uid"));
            }
        }
    );
    return collapsedUids;
};

var _collapseUids = function (grid, collapsedUids) {
    $("#grid .k-grouping-row span[data-uid]")
        .each(function(idx, item) {
            if($.inArray($(item).data("uid"), collapsedUids) >= 0) {
                console.log("collapse: " + $(item).data("uid"))
                grid.collapseGroup($(item).closest("tr"));
            }
        }
    );
};

var refresh = function () {
    var collapsedUids = _getCollapsedUids();
    var grid = $("#grid").data().kendoGrid;
    grid.dataSource.data(createRandomData(50));
    _collapseUids(grid, collapsedUids);
};

$("#refresh").click(refresh);

$("#grid").kendoGrid({
    dataSource: {
        data: createRandomData(50),
        pageSize: 10
    },
    groupable: true,
    sortable: true,
    pageable: {
        refresh: true,
        pageSizes: true
    },
    columns: [ {
            field: "FirstName",
            width: 90,
            title: "First Name"
        } , {
            field: "LastName",
            width: 90,
            title: "Last Name"
        } , {
            width: 100,
            field: "City",
            groupHeaderTemplate: '<span data-uid="City-#=value#">#= value #</span>'
        } , {
            field: "Title"
        } , {
            field: "BirthDate",
            title: "Birth Date",
            template: '#= kendo.toString(BirthDate,"dd MMMM yyyy") #'
        } , {
            width: 50,
            field: "Age"
        }
    ]
});