如何在 Handsontable 的 afterChange 中使用 getCellMeta?

How to use getCellMeta in afterChange at Handsontable?

我正在使用 handsontable js plugin. I want to use getCellMeta function in afterChange 挂钩但无法正常工作。 我在 afterChange 挂钩中使用函数时,函数正在运行。但在 afterChange 挂钩中不起作用。

var container = document.getElementById('t1'),
  options = document.querySelectorAll('.options input'),
  table,
  hot; 

hot = new Handsontable(container, {    
  autoWrapRow: true,
  startRows: 81,
  startCols: 206,
  autoColumnSize : true,  
  stretchH: 'all', 
  afterChange : function(change,source) { 
      if (source === 'loadData') {
        return;
      }   
      var test = this.getCellMeta(change[0],change[1]); // not working, not return "id" meta
      console.log(test);  
  }
});

$.ajax({
  url: 'path',
  type: 'GET',
  dataType: 'json',
  success: function (res) { 
    var data = [], row, pc = 0; 
    for (var i = 0, ilen =  hot.countRows(); i < ilen; i++)
    {
      row = []; 
      for (var ii = 0; ii<hot.countCols(); ii++)
      {   
        hot.setCellMeta(i,ii,'id',res[pc].id);
        row[ii] =   res[pc].price;
        if(pc < (res.length-1)) {

        pc++;
        }
      } 
      data[i] = row;
    }  
    hot.loadData(data);
  }
}); 

var test = this.getCellMeta(0,0); // is working, return "id" meta
console.log(test);  

输出控制台日志我尝试了 afterChange;

输出控制台日志在afterChange中使用;

如何获取更改后的元数据?

谢谢。

您快完成了,您的回调中只有一个小错误:doc for afterChange 指定回调的第一个参数 (changes) 是:

a 2D array containing information about each of the edited cells [[row, prop, oldVal, newVal], ...].

所以,2 个重要细节:

  • 要获取受影响单元格row/col的"meta"(假设只有一个),您需要调用hot.getCellMeta(change[0][0],change[0][1]),例如
  • hot 而不是 this 因为 afterChange 回调函数是从不同的上下文调用的(即在不同的对象上),所以 this 不是调用的正确目标,请参阅 How does the "this" keyword work?

读取整个更改数组的示例:

var hot = new Handsontable(container, {
  /* rest of init... */
  afterChange : function(changes,source) {
      console.log("Changes:", changes, source);
      if (changes) {
          changes.forEach(function(change) {
              var test = hot.getCellMeta(change[0],change[1]);
              console.log(test.id, test); // 'id' is the property you've added earlier with setMeta         
          });
      }
  }
});

查看 demo fiddle,打开 JS 控制台,在 table 中进行任何更改。