萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

ExtJS GridPanel 行拖拽功能完整實現範例

前言

在 ExtJS 應用開發中,實現兩個 GridPanel 之間的行拖拽移動是常見需求。本文提供一個完整的單行拖拽範例,展示如何透過 ddGroup 與 DropTarget 實現跨 Grid 的資料互傳,並防止重複資料新增。

核心概念

  • ddGroup:拖放群組識別碼,來源 Grid 的 ddGroup 必須對應目標 Grid 的 ddGroup,才能建立連結。
  • enableDragDrop:啟用 Grid 內建的行拖曳行為。
  • DropTarget:自訂放置目標,處理 notifyDrop 事件以完成資料搬移邏輯。

完整程式碼範例

1. 建立第一個 Grid

var firstGrid = new Ext.grid.GridPanel({
    ddGroup: 'secondGridDdGroup', // 對應第二個 Grid 的 ddGroup
    store: firstGridStore,
    enableDragDrop: true,         // 啟用行拖曳
    // ... 其他屬性省略
});

2. 建立第二個 Grid

var secondGrid = new Ext.grid.GridPanel({
    ddGroup: 'firstGridDdGroup',  // 對應第一個 Grid 的 ddGroup
    store: secondGridStore,
    enableDragDrop: true,
    // ... 其他屬性省略
});

3. 為第一個 Grid 註冊 DropTarget

var firstGridDropTargetEl = firstGrid.getView().el.dom.childNodes[0].childNodes[1];
var firstGridDropTarget = new Ext.dd.DropTarget(firstGridDropTargetEl, {
    ddGroup: 'firstGridDdGroup',   // 與第二個 Grid 的 ddGroup 一致
    copy: true,                    // 複製模式而非移動
    notifyDrop: function(ddSource, e, data) {
        function addRow(record, index, allItems) {
            // 檢查目標 Store 是否已存在相同 name 的記錄
            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;
    }
});

4. 為第二個 Grid 註冊 DropTarget

var secondGridDropTargetEl = secondGrid.getView().el.dom.childNodes[0].childNodes[1];
var secondGridDropTarget = new Ext.dd.DropTarget(secondGridDropTargetEl, {
    ddGroup: 'secondGridDdGroup',  // 與第一個 Grid 的 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;
    }
});

關鍵邏輯解析

  1. 雙向綁定:兩個 Grid 的 ddGroup 交叉設定,形成雙向拖拽通道。
  2. 去重機制:store.find() 檢查 name 欄位,避免重複資料寫入。
  3. 資料同步:新增至目標 Store 後呼叫 sort() 維持排序,並從來源 Store 移除記錄。
  4. copy: true:設定為複製模式,拖曳時原資料不會立即消失,由 notifyDrop 手動控制移除時機。
  5. 常見問題與注意事項

    • 若 Grid 使用 BufferedRenderer 或 Locking 功能,getView().el.dom.childNodes[0].childNodes[1] 的索引可能不同,需依實際 DOM 結構調整。
    • 大量資料拖拽時建議關閉 copy: true 改用移動模式,或於 notifyDrop 回傳 false 取消預設行為,自行處理批次更新。
    • ExtJS 6+ 現代工具組建議改用 Ext.grid.plugin.DragDrop 外掛,API 更簡潔。

    總結

    透過 ddGroup 配對與 DropTarget 事件處理,即可輕鬆實現 Grid 間的行級拖拽互傳。本範例展示了去重、排序、雙向同步的完整流程,可直接套用於實際專案中。

copyright © 萬盛學電腦網 all rights reserved