Dynamic functions in Sveltekit window[handler] is not defined

46 Views Asked by At

I am trying to call functions dynamically on a CSR flavour of sveltekit without any luck. I get window[handler] is not defined

I have a function that basically acts as a router to other function as shown below.

   function onCellClickHandler(e) {
        if(e.detail.onCellClickHandler) {
        let handler = e.detail.onCellClickHandler;
            // window[handler](e.detail);
            if(handler === 'function1') {
                function1(e.detail)
            }
            if(handler === 'function2') {
                function2(e.detail)
            }
            if(handler === 'function3') {
                function3(e.detail)
            }
        }
    }

However this feels a bit wonky. Is there a way to consolidate this into something more dynamic so that I do not have create a if-block for every function

I tried windowhandler; However that does not seem to work as I get window[handler] is not defined

Any help or suggestions would be much appreciated Thank you in advance

1

There are 1 best solutions below

0
On BEST ANSWER

You could put the handlers in a plain object:

const handlers = {
  function1,
  function2,
  function3,
}

handlers[handler](e.detail);