在cookie中发送扩展的TreeGrid节点

时间:2012-02-08 11:17:39

标签: jquery cookies jqgrid

继续this topic我想在cookie中保存扩展节点。这是最好的方式吗?

我不确定 JSON 数据检查。

为什么expandRow不起作用?

var gridId = "#table";
var grid = $(gridId);
grid.jqGrid({

...

loadComplete: function() {
var ids = grid.jqGrid('getDataIDs');

var cookie = $.cookie(gridId + '_expanded');
var expanded = false;

if (typeof(cookie) == 'string')
var expanded = JSON.parse(cookie);

for (var i=0;i<ids.length;i++) {
var id=ids[i];
var row_data = $(this).jqGrid('getRowData', id);

if (expanded && id in expanded && expanded[id] == 'true')
$(gridId + ' tr#' + id + ' div.treeclick').trigger("click");
//Why it doesn't work?
//grid.jqGrid('expandRow', row_data);

}
}

...

});

function setCookie() {
            var ids = grid.jqGrid('getDataIDs');

            var expanded = Object();
            var string = '';

            for (var i=0;i<ids.length;i++) {    
                var id=ids[i];
                var rowData = grid.jqGrid('getRowData', id);                

                if (rowData.parent != '' && grid.jqGrid('isVisibleNode', rowData) === true)
                    expanded[rowData.parent] = true
            }

            for (e in expanded) 
                string += '"' + e + '":' + '"' + expanded[e] + '",';

            $.cookie(gridId + '_expanded', '{'+ string.substring(0, string.length - 1) + '}', { expires: 365 });    
}

var orgExpandNode = $.fn.jqGrid.expandNode, orgCollapseNode = $.fn.jqGrid.collapseNode;

        $.jgrid.extend({
            expandNode : function(rc) {
                orgExpandNode.call(this, rc);
                setCookie();            
            },
            collapseNode : function(rc) {
                orgCollapseNode.call(this, rc);
                setCookie();                        
            },
});

P.S。我总是得到这个愚蠢的警告:)

您的帖子没有太多上下文来解释代码部分;请更清楚地解释一下你的情景。

1 个答案:

答案 0 :(得分:5)

我建议您使用localStorage而不是Cookie。我在the answer中描述了原因。我根据the demothe answer的演示文稿制作了another one。对于the demo,我使用了我最近answer的一个测试数据。

尝试在the demo扩展一些树节点并使用 F5 重新加载网格。您将看到重新加载后所有展开的行都保持展开状态。

您将在下面找到的演示代码:

var $grid = $('#treegridCompanies'),
    saveObjectInLocalStorage = function (storageItemName, object) {
        if (typeof window.localStorage !== 'undefined') {
            window.localStorage.setItem(storageItemName, JSON.stringify(object));
        }
    },
    removeObjectFromLocalStorage = function (storageItemName) {
        if (typeof window.localStorage !== 'undefined') {
            window.localStorage.removeItem(storageItemName);
        }
    },
    getObjectFromLocalStorage = function (storageItemName) {
        if (typeof window.localStorage !== 'undefined') {
            return JSON.parse(window.localStorage.getItem(storageItemName));
        }
    },
    myColumnStateName = function (grid) {
        return window.location.pathname + '#' + grid[0].id;
    },
    idsOfExpandedRows = [],
    updateIdsOfExpandedRows = function (id, isExpanded) {
        var index = $.inArray(id, idsOfExpandedRows);
        if (!isExpanded && index >= 0) {
            idsOfExpandedRows.splice(index, 1); // remove id from the list
        } else if (index < 0) {
            idsOfExpandedRows.push(id);
        }
        saveObjectInLocalStorage(myColumnStateName($grid), idsOfExpandedRows);
    },
    orgExpandRow = $.fn.jqGrid.expandRow,
    orgCollapseRow = $.fn.jqGrid.collapseRow;

idsOfExpandedRows = getObjectFromLocalStorage(myColumnStateName($grid)) || [];

$grid.jqGrid({
    url: 'SPATEN-TreeGrid2.json',
    datatype: 'json',
    ajaxGridOptions: { contentType: "application/json" },
    jsonReader: {
        id: "CompanyId",
        cell: "",
        root: function (obj) { return obj.rows; },
        page: function () { return 1; },
        total: function () { return 1; },
        records: function (obj) { return obj.rows.length; },
        repeatitems: true
    },
    beforeProcessing: function (data) {
        var rows = data.rows, i, l = rows.length, row, index;
        for (i = 0; i < l; i++) {
            row = rows[i];
            index = $.inArray(row[0], idsOfExpandedRows);
            row[5] = index >= 0; // set expanded column
            row[6] = true;       // set loaded column
        }
    },
    colNames:  ['CompanyId', 'Company'],
    colModel: [
        { name: 'CompanyId', index: 'CompanyId', width: 1, hidden: true, key: true },
        { name: 'Company', index: 'Company', width: 500 }
    ],
    height: 'auto',
    pager: '#pager',
    rowNum: 10000,
    sortable: false,
    treeGrid: true,
    treeGridModel: 'adjacency',
    ExpandColumn: 'Company'
});
$grid.jqGrid('navGrid', '#pager', {edit: false, add: false, del: false, search: false});
$grid.jqGrid('navButtonAdd', '#pager', {
    caption: "",
    buttonicon: "ui-icon-closethick",
    title: "Clear saved grid's settings",
    onClickButton: function () {
        removeObjectFromLocalStorage(myColumnStateName($(this)));
        window.location.reload();
    }
});
$.jgrid.extend({
    expandRow: function (rc) {
        //alert('before expandNode: rowid="' + rc._id_ + '", name="' + rc.name + '"');
        updateIdsOfExpandedRows(rc._id_, true);
        return orgExpandRow.call(this, rc);
    },
    collapseRow: function (rc) {
        //alert('before collapseNode: rowid="' + rc._id_ + '", name="' + rc.name + '"');
        updateIdsOfExpandedRows(rc._id_, false);
        return orgCollapseRow.call(this, rc);
    }
});