多个Slickgrid在同一页面上

时间:2014-05-22 22:11:58

标签: slickgrid

我根据服务器端返回的数据在页面上动态创建多个网格。将所有创建的网格推送到arrayOfGrids。但是,当我必须将数据添加到新行的新单元格时,我遇到了问题。它被添加到最后一个网格。 我怎么能这样做? 我的代码如下所示: -

    var index = 0;
for ( var k = 0; k < steps.length; k++) {
var gridId = "#dataGrid_" + index++;
var grid;
var columns = new Array();
for ( var jj = 0; jj < rows[0].cells.length; jj++) {
    var key = {
        id : rows[0].cells[jj],
        name : rows[0].cells[jj],
        field : rows[0].cells[jj],
        //toolTip : 'Click to sort',
        //width : 200,
        sortable : true,
        editor : Slick.Editors.LongText
    };
    columns[jj] = key;
}
var data = [];
for ( var i = 1; i < rows.length; i++) {
    var tempData = (data[i - 1] = {});
    var title = null;
    var val = null;
    for ( var q = 0; q < rows[i].cells.length; q++) {
        title = rows[0].cells[q];
        val = rows[i].cells[q];
        tempData[title] = val;
    }
}

var options = {
    enableCellNavigation : true,
    editable: true,
    asyncEditorLoading: false,
    enableColumnReorder: true,
    enableAddRow: true,
    autoHeight: true,
    leaveSpaceForNewRows:false,
    explicitInitialization: true
};
var myGrid = $("<div id='"+gridId+"' style='width:400px;'></div>");
grid = new Slick.Grid(myGrid, data, columns, options);
myGrid.appendTo($("#tableData"));
grid.init();
grid.onAddNewRow.subscribe(function(e,args){
    // Always adds to last grid ?

});
arrayOfGrids.push(grid);
}

1 个答案:

答案 0 :(得分:1)

确定。我的工作基于javascript闭包。 Best是将网格创建代码提取到一个单独的函数中,并在for循环中调用该函数。在那之后,一切都像魅力一样。

function createGrid(gridId, rows) {
var grid;
var colIndex = 0;
var columns = new Array();
for ( var jj = 0; jj < rows[0].cells.length; jj++) {
    var key = {
        id : rows[0].cells[jj],
        name : rows[0].cells[jj],
        field : rows[0].cells[jj],
        //toolTip : 'Click to sort',
        //width : 200,
        sortable : true,
        editor : Slick.Editors.LongText
    };
    columns[jj] = key;
}
var data = [];
for ( var i = 1; i < rows.length; i++) {
    var tempData = (data[i - 1] = {});
    var title = null;
    var val = null;
    for ( var q = 0; q < rows[i].cells.length; q++) {
        title = rows[0].cells[q];
        val = rows[i].cells[q];
        tempData[title] = val;
    }
}

var options = {
    enableCellNavigation : true,
    editable: true,
    asyncEditorLoading: false,
    enableColumnReorder: true,
    enableAddRow: true,
    autoHeight: true,
    leaveSpaceForNewRows:false,
    explicitInitialization: true
};
var myGrid = $("<div id='"+gridId+"' style='width:400px;'></div>");
grid = new Slick.Grid(myGrid, data, columns, options);
myGrid.appendTo($("#tableData"));
grid.init();
arrayOfGrids.push(grid);

 grid.onAddNewRow.subscribe(function (e, args) {

var item = args.item;
     grid.invalidateRow(data.length);
     data.push(item);
     grid.updateRowCount();
     grid.render();
 });

}

并从for循环中调用该函数。