兩個 GridPanel 之間互相拖拽數據,是 ExtJs 裡很常見的交互。實現的核心是配置 ddGroup 讓拖放源與目標配對,再在目標上實現 DropTarget 處理落下後的數據搬遷。
// 第一個 GRID
var firstGrid = new Ext.grid.GridPanel({
ddGroup: 'secondGridDdGroup', // 引用第二個 GRID 的組名
store: firstGridStore,
enableDragDrop: true, // 啟動選中行的拖動行為
...其他屬性省略
});
// 第二個 GRID
var secondGrid = new Ext.grid.GridPanel({
ddGroup: 'firstGridDdGroup', // 引用第一個 GRID 的組名
store: secondGridStore,
enableDragDrop: true,
...其他屬性省略
});
關鍵在於交叉:firstGrid 的 ddGroup 要寫成 secondGrid 將要監聽的那個組名,反之亦然。這樣 firstGrid 裡被拖起的元素才會被 secondGrid 的放置目標接收。
var firstGridDropTargetEl = firstGrid.getView().el.dom.childNodes[0].childNodes[1];
var firstGridDropTarget = new Ext.dd.DropTarget(firstGridDropTargetEl, {
ddGroup: 'firstGridDdGroup', // 與 secondGrid 的 ddGroup 相同
copy: true,
notifyDrop: function (ddSource, e, data) {
function addRow(record, index, allItems) {
var foundItem = secondGridStore.find('name', record.data.name);
if (foundItem == -1) {
firstGridStore.add(record);
firstGridStore.sort('name', 'ASC');
ddSource.grid.store.remove(record);
}
}
Ext.each(ddSource.dragData.selections, addRow);
return true;
}
});
var secondGridDropTargetEl = secondGrid.getView().el.dom.childNodes[0].childNodes[1];
var secondGridDropTarget = new Ext.dd.DropTarget(secondGridDropTargetEl, {
ddGroup: 'secondGridDdGroup', // 與 firstGrid 的 ddGroup 相同
copy: true,
notifyDrop: function (ddSource, e, data) {
function addRow(record, index, allItems) {
var foundItem = secondGridStore.find('name', record.data.name);
if (foundItem == -1) {
secondGridStore.add(record);
secondGridStore.sort('name', 'ASC');
ddSource.grid.store.remove(record);
}
}
Ext.each(ddSource.dragData.selections, addRow);
return true;
}
});
notifyDrop 是整個流程的核心。它從 ddSource.dragData.selections 拿到被拖動的所有選中記錄(支持多選批量搬遷),逐條執行:先在目標 store 中查重,不存在才添加,然後排序,最後從源 store 移除。
這裡有一處值得修正的地方:第一個 DropTarget 的 notifyDrop 裡,查重的對象寫的是 secondGridStore,但添加和移除操作的卻是 firstGridStore。也就是說從 secondGrid 拖到 firstGrid 時,它去 secondGrid 查了重,結果不一致。正確做法應該是查 firstGridStore。這類複製粘貼留下的 bug 在拖拽代碼裡相當常見。
copy: true 表示放置時保留原數據,但示例中又顯式調用了 remove,兩者語義上存在衝突。若想要「移動」效果,應把 copy 設為 false 並移除記錄;若想「複製」,則不應刪除源記錄。
另外,getView().el.dom.childNodes[0].childNodes[1] 這種硬編碼的 DOM 路徑非常脆弱,一旦 ExtJs 版本變化導致內部結構調整就會失效。更穩妥的做法是使用 grid 的 view 提供的 dropEl 或直接用 grid 自身的元素作為放置目標。
最後提醒一點:ExtJs 3.x 與 4.x 以上的拖放 API 差異不小,4.x 之後更推薦使用 Ext.grid.plugin.DragDrop 配合 viewConfig 的 plugins 配置,代碼量更少,也不必手動定位 DOM 節點。上面這套寫法屬於 3.x 風格,遷移時需要留意。