首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

ExtJS 6.0 樹節點重命名:setText 廢用後的正確 API 使用指南

     編輯:程式設計疑難解答

版本遷移痛點

ExtJS 6.0 移除了樹節點的 setText() 方法,導致舊代碼 node.setText('新名稱') 失效,開發者需遷移至新 API。

官方推薦方案:setConfig()

// 獲取樹節點(假設已選中)
var node = tree.getSelectionModel().getSelection()[0];

// 正確重命名方式
node.setConfig({
    text: '新節點名稱'
});

// 或使用 set() 方法(內部調用 setConfig)
node.set('text', '新節點名稱');

API 文檔參考

官方文檔:Ext.data.NodeInterface.setConfig

完整操作示例

1. 單節點重命名(推薦)

function renameNode(node, newText) {
    if (!node) return false;
    
    // 校驗輸入
    if (!newText || newText.trim() === '') {
        Ext.Msg.alert('提示', '節點名稱不能為空');
        return false;
    }
    
    // 執行重命名
    node.set('text', newText.trim());
    
    // 可選:持久化到後端
    syncNodeToServer(node);
    
    return true;
}

2. 批量重命名(遞歸處理)

function renameNodeAndChildren(node, prefix) {
    node.set('text', prefix + node.get('text'));
    
    if (node.hasChildNodes()) {
        node.eachChild(function(child) {
            renameNodeAndChildren(child, prefix);
        });
    }
}

3. 編輯器模式雙擊重命名(用戶體驗)

// TreePanel 配置
plugins: {
    ptype: 'cellediting',
    clicksToEdit: 2
},
columns: [{
    xtype: 'treecolumn',
    text: '名稱',
    dataIndex: 'text',
    flex: 1,
    editor: {
        xtype: 'textfield',
        allowBlank: false
    }
}],
listeners: {
    edit: function(editor, context) {
        // context.record 即被編輯節點
        syncNodeToServer(context.record);
    }
}

底層原理:NodeInterface 混入模式

ExtJS 樹節點實際是 Ext.data.TreeModel 實例,混入了 NodeInterface 提供樹操作方法。set()/setConfig() 繼承自 Ext.data.Model,觸發以下流程:

  1. 更新內部 data.text 屬性
  2. 標記節點 dirty = true
  3. 觸發 update 事件 → 視圖自動刷新
  4. 若啟用 autoSync,自動發送同步請求

避坑指南

錯誤做法問題正確替代
node.data.text = 'new'繞過模型系統,視圖不更新,持久化失效node.set('text', 'new')
node.setText('new')方法不存在,拋出 TypeErrornode.set('text', 'new')
直接修改 store 數據破壞節點父子關係,樹結構損壞通過節點 API 操作

版本兼容性策略

// 兼容性封裝:支持 ExtJS 4/5/6/7
Ext.data.NodeInterface.override({
    setText: function(text) {
        // 統一內部實現
        this.set('text', text);
        return this;
    }
});

// 之後所有版本均可使用
node.setText('新名稱'); // 安全調用
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved