萬盛學電腦網

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

ExtJS 4 TreePanel 拖曳排序實作:viewConfig plugins 與事件監聽

核心配置:viewConfig

在 TreePanel 中啟用拖曳只需配置 viewConfig,關鍵在 ptype: 'treeviewdragdrop'。

Ext.define('MyApp.view.MyTree', {
  extend: 'Ext.tree.Panel',
  alias: 'widget.mytree',
  title: '部門架構',
  rootVisible: false,
  store: {
    type: 'tree',
    root: {
      expanded: true,
      children: [
        {text: '總經理室', leaf: true, id: 'dept1'},
        {text: '研發部', expanded: true, children: [
          {text: '前端組', leaf: true, id: 'dept2'},
          {text: '後端組', leaf: true, id: 'dept3'}
        ]},
        {text: '行銷部', leaf: true, id: 'dept4'}
      ]
    }
  },
  // 關鍵配置區
  viewConfig: {
    plugins: {
      ptype: 'treeviewdragdrop',
      appendOnly: true  // true: 只能拖曳到非葉節點(成為子節點);false: 可插入同層
    },
    listeners: {
      // 放置完成前 (可攔截)
      beforedrop: function(node, data, overModel, dropPosition, dropHandlers) {
        // data.records[0] 為被拖曳的節點
        // overModel 為目標節點
        // dropPosition: 'before', 'after', 'append'
        
        console.log('準備移動:', data.records[0].get('text'), '→', overModel.get('text'), '位置:', dropPosition);
        
        // 例:禁止移動到葉節點內部
        if (overModel.isLeaf() && dropPosition === 'append') {
          Ext.Msg.alert('提示', '不可移動到葉節點內部');
          return false; // 取消 drop
        }
        
        // 例:若目標為葉節點,自動轉為非葉節點 (展開資料夾)
        if (overModel.isLeaf()) {
          overModel.set('leaf', false);
          overModel.set('expanded', true);
        }
      },
      
      // 放置完成後
      drop: function(node, data, overModel, dropPosition, eOpts) {
        var movedNode = data.records[0];
        var targetNode = overModel;
        
        console.log('已移動:', movedNode.get('text'), '到', targetNode.get('text'));
        
        // 同步至後端
        Ext.Ajax.request({
          url: '/api/departments/move',
          method: 'POST',
          params: {
            nodeId: movedNode.get('id'),
            targetId: targetNode.get('id'),
            position: dropPosition  // 'before', 'after', 'append'
          },
          success: function(response) {
            var result = Ext.decode(response.responseText);
            if (!result.success) {
              Ext.Msg.alert('失敗', result.msg);
              // 可選:store.reload() 還原
            }
          },
          failure: function() {
            Ext.Msg.alert('錯誤', '網路異常,移動可能未同步');
          }
        });
      }
    }
  }
});

兩棵樹之間拖曳

若需在 兩棵不同 TreePanel 之間 拖曳,兩棵樹都必須配置相同的 viewConfig:

// Tree A
viewConfig: {
  plugins: {ptype: 'treeviewdragdrop', dragGroup: 'deptGroup', dropGroup: 'deptGroup'},
  listeners: { beforedrop: ..., drop: ... }
}

// Tree B
viewConfig: {
  plugins: {ptype: 'treeviewdragdrop', dragGroup: 'deptGroup', dropGroup: 'deptGroup'},
  listeners: { beforedrop: ..., drop: ... }
}

dragGroup / dropGroup 機制

  • dragGroup:此樹的拖曳來源屬於哪個群組
  • dropGroup:此樹接受哪個群組的拖曳
  • 相同群組名稱即可互相拖曳

完整可執行範例 (單檔)

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>ExtJS 4 Tree Drag & Drop</title>
  <link rel="stylesheet" href="https://cdn.sencha.com/ext/trial/4.2.1/resources/css/ext-all.css">
  <script src="https://cdn.sencha.com/ext/trial/4.2.1/ext-all.js"></script>
  <script>
    Ext.onReady(function() {
      var store = Ext.create('Ext.data.TreeStore', {
        root: {expanded: true, children: [
          {text: '資訊部', id: '1', expanded: true, children: [
            {text: '開發組', id: '1-1', leaf: true},
            {text: '維運組', id: '1-2', leaf: true}
          ]},
          {text: '財務部', id: '2', leaf: true}
        ]}
      });

      Ext.create('Ext.tree.Panel', {
        title: '組織架構拖曳排序',
        width: 400,
        height: 300,
        renderTo: Ext.getBody(),
        store: store,
        rootVisible: false,
        viewConfig: {
          plugins: {ptype: 'treeviewdragdrop', appendOnly: false},
          listeners: {
            beforedrop: function(node, data, overModel, dropPosition) {
              if (overModel.isLeaf() && dropPosition === 'append') {
                Ext.Msg.alert('限制', '不可放入葉節點');
                return false;
              }
              if (overModel.isLeaf()) overModel.set('leaf', false);
            },
            drop: function(node, data, overModel, dropPosition) {
              var moved = data.records[0].get('text');
              var target = overModel.get('text');
              Ext.Msg.alert('完成', moved + ' 已移動到 ' + target + ' (' + dropPosition + ')');
            }
          }
        }
      });
    });
  </script>
</body>
</html>

dropPosition 三種值說明

值視覺位置資料結構變化
before目標節點之前成為目標的前一個同層節點
after目標節點之後成為目標的後一個同層節點
append目標節點內部 (子節點)成為目標的最後一個子節點

進階技巧

  1. 自訂拖曳代理樣式:覆寫 getDragText 回傳自定 HTML
  2. 鎖定特定節點不可拖曳:在節點資料加 draggable: false,或 beforedragstart 事件返回 false
  3. 多選拖曳:treeviewdragdrop 預設支援 Ctrl/Cmd 多選,data.records 為陣列
  4. 動態載入子節點:append 時若目標未展開,需先 overModel.expand() 再移動

總結

ExtJS 4 Tree 拖曳核心在於 viewConfig.plugins.ptype='treeviewdragdrop',搭配 beforedrop 驗證與 drop 後端同步。兩樹互拖需設定相同 dragGroup/dropGroup。appendOnly 參數控制是否允許同層插入。

copyright © 萬盛學電腦網 all rights reserved