2010-08-23 176 views
4

努力尋找一些代碼來輕鬆理解。在Dojo datagrid中添加一行

如何添加行並清除Dojo數據網格中的所有行(版本1.4.2)。可以說這些數據是2列,包含customerID和地址。

我使用

dojo.data.ItemFileWriteStore 

存儲值 - 但同樣不能肯定應如何使用。

它不能那麼難。

乾杯。

回答

4

您可以使用grid.store從網格中獲取數據存儲引用,然後您可以使用store.newItem()在商店中創建新項目。這個新項目作爲網格中的新行添加。例如,store.newItem({customerID : 1, address : "Somewhere"})

要清除所有的行,您可以循環在數據存儲中的所有項目,並使用deleteItem()刪除所有項目,或者使用內部功能_clearData()在數據網格中刪除所有的行,或使用setStore()設置一個新的電子商店。我更喜歡使用空的商店來重置網格。

1

我完成這一個例子...該代碼是在這裏

 
//First we create the buttons to add/del rows 
var addBtn = new dijit.form.Button({ 
     id: "addBtn", 
     type: "submit", 
     label: "Add Row" 
    }, 
    "divAddBtn");//div where the button will load

var delBtn = new dijit.form.Button({ id: "delBtn", type: "submit", label: "Delete Selected Rows" }, "divDelBtn");

//Connect to onClick event of this buttons the respective actions to add/remove rows. //where grid is the name of the grid var to handle. dojo.connect(addBtn, "onClick", function(event) { // set the properties for the new item: var myNewItem = { id: grid.rowCount+1, type: "country", name: "Fill this country name" }; // Insert the new item into the store: // (we use store3 from the example above in this example) store.newItem(myNewItem); });

dojo.connect(delBtn, "onClick", function(event) { // Get all selected items from the Grid: var items = grid.selection.getSelected(); if (items.length) { // Iterate through the list of selected items. // The current item is available in the variable // "selectedItem" within the following function: dojo.forEach(items, function(selectedItem) { if (selectedItem !== null) { // Delete the item from the data store: store.deleteItem(selectedItem); } // end if }); // end forEach } // end if });
4

以上的答案是正確的,但你也需要調用寫商店save()「落實」的轉變。保存時,使用商店(例如datagrid)的小部件將自行刷新。

另外,newItem()返回您剛剛創建的新項目,所以如果您不想傳遞對象到newItem只是修改其返回值,然後save()商店。

僞代碼:

var i = store.newItem({}); 

store.setValue(i,"newattribute1","new value"); 
store.setValue(i,"newattribute2","new value 2"); 

store.save(); 

Here is the relevant docs for ItemFileWriteStore,告訴如何使用newItem()setValue(),並save()

而不是deleteItem,你應該使用setStore(new ItemFileWriteStore()),但我懷疑當你這樣做時有內存泄漏,小心。這使得一個新的空白商店與網格一起使用。