萬盛學電腦網

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

ExtJS RowExpander 預設展開指定行:store 載入完成後回呼 toggleRow 實作

需求場景

ExtJS Grid 使用 `RowExpander` 外掛時,預設所有行摺疊。業務需求:資料載入完成後,自動展開符合條件的行(如 `StatusID === '3'`)。

核心實作

// 1. 定義展開邏輯
function expandMatchingRows() {
  const store = ProdRequireInfoStore; // Grid 的 Store
  const rowsToExpand = [];

  store.each(function (record, index) {
    if (record.get("StatusID") === "3") {
      rowsToExpand.push(index);
    }
  });

  // 批次展開
  rowsToExpand.forEach(function (rowIndex) {
    expander.toggleRow(rowIndex); // expander 為 RowExpander 實例
  });
}

// 2. 掛載在 Store 載入完成回呼
ProdRequireInfoStore.load({
  params: {
    dir: "DESC",
    start: 0,
    limit: 20,
    KeyWord: ""
  },
  callback: expandMatchingRows, // 載入完成後自動執行
  scope: this
});

關鍵點解析

  • store.each(fn):遍歷所有 record,回傳 `(record, index)`,比 `for` 迴圈更符合 ExtJS 風格。
  • record.get("field"):取得欄位值,而非 `record.data.field`(雖然也可用,但不建議直接存取內部屬性)。
  • expander.toggleRow(index):RowExpander 公開方法,切換指定行展開/摺疊狀態。
  • callback:`store.load()` 選項,在資料**完全載入並處理完畢**後觸發,確保行已渲染可操作。

進階:避免重複展開 / 狀態同步

function expandMatchingRows() {
  const store = ProdRequireInfoStore;
  store.each(function (record, index) {
    const shouldExpand = record.get("StatusID") === "3";
    const isExpanded = expander.state[index] === true; // 內部狀態記錄

    if (shouldExpand && !isExpanded) {
      expander.toggleRow(index);
    } else if (!shouldExpand && isExpanded) {
      expander.toggleRow(index); // 可選:摺疊不符合條件的行
    }
  });
}

效能考量

  • 大量資料(>1000 行)逐行 `toggleRow` 會觸發多次 DOM 重排,建議:
  • 先收集索引,再用 `Ext.suspendLayouts()` / `resumeLayouts()` 包裹
  • 或改用 `expander.expandAll()` 後再摺疊不需要的(視比例決定)

現代 ExtJS (6/7+) 寫法差異

  • RowExpander 現為 `plugin: "rowexpander"` 配置
  • 取得 plugin 實例:`grid.getPlugin("rowexpander")` 或 `grid.plugins.find(p => p.ptype === "rowexpander")`
  • Store 事件改用 `store.on("load", fn, this, { single: true })` 或 `store.load({ callback: fn })`

總結

關鍵在於 **Store `load` 回呼中遍歷 record、收集索引、呼叫 `expander.toggleRow(index)`**。注意取得 plugin 實例時機、大量資料效能優化,以及與 ExtJS 版本 API 差異對應。

copyright © 萬盛學電腦網 all rights reserved