Javascript: Using a string as a function

I’m working on a game framework where “trigger” objects have a property “clickhandler” that contains the name of the function to be executed on click.

All items in the game are listed with their properties in an itemList. This allows a great deal of flexibility in what types of games can be created, but I ran into a problem trying to use the string that designated the function.

I first tried listing the function name as a string containing the argument. “drawerOpener(drawer1)”

===item listing===
var itemList = {
   …list of items...
drawerhandle1:{
    container:'drawerHandlesLayer',
    type:'trigger',
    clickHandler:'drawerOpener(drawer1)'
}
=======how used in game==========
if(itm.type=='trigger'){ 
     item.on('mousedown touchstart', function() { 
     itm.clickHandler;
);
======================

That got me only the error

“drawerOpener(drawer1) is not a function”.

I next tried listing the function name without the string quotes, i.e.:

===item listing===
drawerhandle1:{
    container:'drawerHandlesLayer',
    type:'trigger',
    clickHandler:drawerOpener(drawer1)
}
======================

but of course it only causes the drawerOpener() function to be immediately executed inline as the item list is read in – not at all what I wanted.

What does work is to pass in the function name and arguments separately:

===item listing===
drawerhandle1:{
    container:'drawerHandlesLayer',
    type:'trigger',
    clickHandler:'drawerOpener',
    args:'drawer1',
}
======

 var func = itm.clickHandler;
var args = itm.args; 
if(itm.type=='trigger'){ 
     item.on('mousedown touchstart', function() { 
     window[func](args); 
);

Resources