更改表名时,Excel JavaScript API中是否有事件会触发?

问题描述

对于我正在开发的Excel加载项,我需要知道何时更改表名。 “Events” section for Table没有onNameChanged或类似名称。我尝试过onChanged是否也涵盖了名称更改,但是在下面的代码段中,它不是由表的名称更改触发的。代码段中的其他处理程序也不会触发。我已经在Office Online和Mac版Excel(v16.39)中测试了该代码段。更改表名时是否还会触发另一个事件?

async function run() {
  await Excel.run(async (context) => {
    const table = context.workbook.tables.add("A1:B2",true);
    table.load('worksheet');
    await context.sync();
    const createHandler = (name) => (async () => {
      console.log(`Received event: ${name}`);
    });
    table.onChanged.add(createHandler('Table.onChanged'));
    context.workbook.tables.onChanged.add(createHandler('TableCollection.onChanged'));
    context.workbook.tables.onAdded.add(createHandler('TableCollection.onAdded'));
    context.workbook.tables.onDeleted.add(createHandler('TableCollection.onDeleted'));
    table.worksheet.onChanged.add(createHandler('Worksheet.onChanged'));
    await context.sync();
    table.name = 'TestTable';
    await context.sync();
  });
}

解决方法

很遗憾,Office JS Excel API当前不支持table.onNameChanged事件。尽力而为,您尝试使用table.onChanged,但是,table.onChanged仅在此表中单元格中的数据更改时出现。

因此,我建议您可以在uservoice提交请求并对此请求进行投票,也可以在此请求中分享您的方案。

,

鉴于您希望重命名Excel(不是JavaScript)中的表格时触发一个事件,并且重命名时不会触发onChanged上的假定Table事件,我的解决方法是如下:

Worksheet(包含[Table])上监听onChanged事件,以便侦听所有表的数据更改。事件触发时,请检查worksheet.tables中的Table),以更改名称(与旧名称的Map比较):

const map = new Map();
worksheet.tables.forEach((table,i) => {
    const newName = table.name;
    const key = `${worksheet.id}-${i}`;
    map.set(key,newName);
}

worksheet.onChanged.add(() => {
  worksheet.tables.forEach((table,i) => {
    const newName = table.name;
    const key = `${worksheet.id}-${i}`;
    
    let oldName;
    if (map.has(key)) {
      oldName = map.get(key);
    } else {
      map.set(key,newName);
    }

    if (oldName !== newName) {
      console.log(`Name changed from ${oldName} to ${newName}`);
      console.log(`For table ${key}`);
    }
  });
});

附带说明:您始终可以通过将对象包装到Proxy中来侦听Javascript中的更改。这是一个示例:

let obj = {
    name: 'harry potter',age: 27,};

// we want to listen for changes on name
// so wrap object in Proxy
obj = new Proxy(obj,{
    set(obj,prop,newval) {
        if (prop === 'name') {
            // put your changing logic here
            // or fire an event listener
            console.log("Name has changed");
        }

        // default behavior to store value
        obj[prop] = newval;
        return true;
    } 
})

obj.name = 'john smith';
// outputs 'Name has changed'

在此处了解有关代理的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...