我目前正在使用Excel加载项。
我已经尝试了几个小时才能在Excel Online中添加/删除绑定。我在每个绑定上附加一个处理程序。如果我添加,删除(),然后再次添加给定范围的绑定(例如A1:A100),则事件处理程序将被调用两次。
我在Script Lab的帮助下复制了我的代码:https://gist.github.com/pasdechancee/b945008386804b426a127a0125d5b3ec
这是要点中的javascript代码:
$("#run").click(() => tryCatch(run));
async function run() {
await removeListeners()
await registerListeners()
await removeListeners()
await registerListeners()
// Expected outcome : when we change a value in A1:A100, an event
// is fired only ONCE (since the first listeners was removed) instead of twice
}
/** Default helper for invoking an action and handling errors. */
async function tryCatch(callback) {
try {
await callback();
} catch (error) {
// Note: In a production add-in, you'd want to notify the user through your add-in's UI.
console.error(error);
}
}
async function listenersCallback({binding}){
console.log(binding.id + " event")
}
/* delete all bindings */
function removeListeners() {
return Excel.run(async context => {
const bindings = context.workbook.bindings.load("items");
await context.sync();
for (let i = 0; i < bindings.items.length; i++) {
bindings.items[i].delete();
}
await context.sync();
}).catch(err => console.log(err));
}
/* register my binding */
function registerListeners() {
return Excel.run(async context => {
const newBinding = context.workbook.bindings.add(
"A1:A100",
"Range",
"cc1c.onDataChangedBinding:" + "A1:A100"
);
newBinding.onDataChanged.add(listenersCallback);
await context.sync();
}).catch(err => console.log(err));
}
由于某种原因,如果我使绑定ID唯一,则eventListener仅被调用一次,因此这可能是一种解决方法...但是我仍然想解决这个问题。
我是Office js的新手,所以我可能搞砸了context.sync()调用之类的东西?
任何对此的帮助将不胜感激! :)