I've been trying to execute the event handler function just when the format function is called and then remove the event handler function. In this way the period of listening to calculated functions is limited.
This sample Remove an event handler declares the function but I'm a little bit confused with the place to call the "remove()".
async function format() {
var eventResult;
await Excel.run(async (context) => {
const sheet = context.workbook.worksheets.getActiveWorksheet();
eventResult = sheet.onCalculated.add(function(event){
return Excel.run(function (context){
//Do some things
return context.sync().then(function () {
//Do some things
})
.then(()=>{
// remove(); -> error: eventResult is not defined
})
});
});
// remove(); -> error: eventResult is not defined
return context.sync();
});
}
The remove function:
async function remove() {
await Excel.run(eventResult.context, function (context) {
eventResult.remove();
return context.sync()
.then(function() {
eventResult = null;
console.log("Event handler successfully removed.");
});
})
}