Remove event handler excel javascript api

Viewed 163

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.");
      });
})
}
1 Answers

I think the problem is that the local variable "eventResult" is not available for "remove()" function. Try one of the below options will solve the issue.

  1. Move the code "var eventResult;" above(outside) of "async function format(){...}".
  2. Make "eventResult" as input parameter for "remove()" function, which will look like "async function remove(eventResult)"
Related