如何使setItems在SlickGrid中正常工作?

时间:2015-03-05 14:48:53

标签: javascript slickgrid

我有这个简单的代码:

var columnsTest = [ 
    {id: "testId", name: "ID", field: "id", width: 50},
    {id: "field1", name: "field1", field: "field1", width: 200},
    {id: "field2", name: "field2", field: "field2", width: 200}
]

function saveTest() {
    var itemFields = [];
    itemFields = dataViewTest.getItemById( dataViewTest.getItem(gridTest.getSelectedRows()).id );

    itemFields['field1'] =  $('#field1').val();
    itemFields['field2'] =  $('#field2').val(); 

    var data = JSON.stringify(itemFields);
    console.log("data: " + data);
    dataViewTest.beginUpdate();
    dataViewTest.setItems(itemFields, "id");
    dataViewTest.endUpdate();   
    dataViewTest.refresh(); 
}

$(function() {
    dialogTest = $( "#test_form" ).dialog({
        autoOpen: false,
        height: 480,
        width: 600,
        modal: true,
        buttons: {
            "Save": function() { saveTest(); },
            "Cancel": function() { dialogCustomer.dialog( "close" ); }
        }
    });

    dataViewTest = new Slick.Data.DataView({ inlineFilters: true });

    gridTest = new Slick.Grid($("#test_grid"), dataViewTest, columnsTest, optionsTest);
    gridTest.setSelectionModel(new Slick.RowSelectionModel());
    gridTest.registerPlugin( new Slick.AutoTooltips({ enableForHeaderCells: true }) );
    pagerTest = new Slick.Controls.Pager(dataViewTest, gridTest, $("#test_pager"));

    dataViewTest.onRowsChanged.subscribe(function (e, args) {
      gridTest.invalidateRows(args.rows);
      gridTest.render();
    });         

    $( "#add_test" ).button().on('click', function() {
        dialogTest.dialog("option", "title", "Create New");
        dialogTest.dialog( "open" );
    }); 
});

在console.log中我有:

data: {"id":"187","field1":"aaaaaaa","field2":"bbbbbbb"}

但是当我尝试保存控制台时仍然说:"未捕获每个数据元素都必须实现一个唯一的“id”#39;财产" ...我错过了什么? 虽然我有id属性,甚至传递给setItems的objectIdProperty可选参数...

提前谢谢! 干杯! 路易

1 个答案:

答案 0 :(得分:0)

我不确定你的函数之前是如何部分工作的,因为gridTest.getSelectedRows()返回一个数组,因此dataViewTest.getItem(selectedRows)应该出错。此外,由于您似乎只想更新单个项目,因此您不会调用dataViewTest.setItems(),因为这是为了同时更新多个项目并采用一组对象/行/项目,而不仅仅是一。这可能是你想要的:

function saveTest() {
    var rows = gridTest.getSelectedRows(); // array of row indices: [5,8,21,42]
    var item = gridTest.getDataItem(rows[0]); // get the actual data item for the first selected row

    // update the properties for the item
    item.field1 = $('#field1').val();
    item.field2 = $('#field2').val(); 

    console.log("data:", item);

    // tell your dataview to update the item
    dataViewTest.updateItem(item.id, item);
}