I'm using ScriptLab to play with event handlers. Every time I run a script, a new event handler is registered. I know how to remove one event handler, but everytime the code execution is refreshed, it is not possible anymore to delete the event handler registered in the last execution, so they get stacked and execute with the new code.
I'd like to know if it is possible to remove all event handlers from a worksheet, table, workbook, etc.
Maybe a way to access a collection of registered event handlers and allow to delete them, the same way we can do with JavaScript.
EDIT: code for context
$("#run").click(() => tryCatch(run));
$("#remove").click(() => tryCatch(remove));
let eventResult;
async function run() {
await Excel.run(async (context) => {
const worksheet = context.workbook.worksheets.getItem("Sample");
eventResult = worksheet.onSelectionChanged.add(handleSelectionChange);
await context.sync();
console.log("Event handler successfully registered for onSelectionChanged event in the worksheet.");
});
}
async function handleSelectionChange(event) {
await Excel.run(async (context) => {
await context.sync();
console.log("Address of current selection: " + event.address);
});
}
async function remove() {
await Excel.run(eventResult.context, async (context) => {
eventResult.remove();
await context.sync();
eventResult = null;
console.log("Event handler successfully removed.");
});
}
/** 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);
}
}
See that it is easy to remove a handler if you store it in a variable (eventResult
). But as soon as I make any change to the ScriptLab code pane, every variable is resetted, but the event is still active in the worksheet.
I'd like a way to remove the event(s) even if the code goes out of context and variables lose state.