我目前正在开发一个 Excel 加载项。
我已经尝试了几个小时在 Excel Online 中添加/删除绑定。我正在为每个绑定附加一个处理程序。如果我添加、删除(),然后再次为给定范围添加绑定(例如:A1:A100),则事件处理程序被调用两次。
我用 Script Lab 做了一个要点来重现我的代码:https ://gist.github.com/pasdechancee/b945008386804b426a127a0125d5b3ec
这是来自 gist 的 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() 调用或其他什么?
对此的任何帮助将不胜感激!:)