从单元格组件内部检测行选择更改

Detect row selection change from inside a cell component

我在应用程序中使用 Tabulator 来满足某些数据需求,并创建了一些自定义 cell.s

我目前有一个带有 "Edit" 按钮的自定义单元格,用于切换行选择及其可编辑性。网格外部还有一个按钮,允许选择所有行(如屏幕截图所示)

我想做的是当突出显示该行时(通过单击 "Edit" 按钮或选择所有行时,将按钮从 "Edit" 更改为 "Cancel"以编程方式)。

在单元格中,我可以通过 cell.getRow().isSelected() 获取当前行选择,但我没有看到检测特定行选择何时更改的方法。

我想到的一个解决方案是使用 CSS 到 hide/show "Edit" 或 "Cancel" 按钮,因为 Tabulator 将添加 class tabulator-selected 到任何突出显示的内容。但这似乎更像是一个 hack。

提前感谢您的想法、意见和评论!


如果相关,我使用 Tabulator 包装在 Vue 组件中。自定义单元格目前只是香草 JS。

我想出了一个合适的方法来检测单元格中的行选择变化。它使用 MutationObserver API 并检查 tabulator-selected CSS class.

的行元素

(我也开了一个feature request on GitHub,所以以后可能会有不同的处理方式)

/**
 * A custom formatter/cell to enable the selection of an individual row
 *
 * @param {Object} cell Tabulator Cell object
 * @returns {HTMLElement}
 */
export default function(cell) {
  const checkbox = document.createElement('input')
  checkbox.type = 'checkbox'
  checkbox.onchange = function() {
    cell.getRow().toggleSelect()
  }

  // Callback function to execute when mutations are observed
  function mutationCallback(mutationsList) {
    for (let mutation of mutationsList) {
      // if you are using something other than a checkbox, you would perform the element changes in there
      checkbox.checked = mutation.target.classList.contains('tabulator-selected')
    }
  }

  // Create an observer to only watch for attribute changes (like CSS classes) and activate it
  const rowEl = cell.getRow().getElement()
  // list of all available config options: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit
  const config = { attributes: true, attributeFilter: ['class'] }
  const observer = new MutationObserver(mutationCallback)
  observer.observe(rowEl, config)

  return checkbox
}

正确的方法是在单元格上使用格式化程序,根据行的选定状态设置切换的选定状态,可以使用 cell.getRow().isSelected()

检索

然后您可以使用 rowSelectionChanged 回调和 reformat 行组件上的函数,用于在其选择状态更改时触发该行的重新格式化:

var table = new Tabulator("#example-table", {
    rowSelectionChanged:function(data, rows){
        rows.forEach(function(row){
            row.reformat();
        });
    },
});

Tabulator 中内置了回调,可以在行选择发生更改时告诉您,rowSelectedrowDeselectedrowSelectionChanged。这些的完整文档可以在 Callbacks Documentation

中找到

只有在格式化程序中更改单元格的格式才是安全的,因此您想观察一行上选择的更改,然后触发该行的重新格式化:

var table = new Tabulator("#example-table", {
    rowSelectionChanged:function(data, rows){
        rows.forEach(function(row){
            row.reformat();
        });
    },
});