This question already has an answer here:
I got a string like:
settings.functionName + '(' + t.parentNode.id + ')';
that I want to translate into a function call like so:
clickedOnItem(IdofParent);
This of course will have to be done in JavaScript. When I do an alert on settings.functionName + '(' + t.parentNode.id + ')';
it seems to get everything correct. I just need to call the function that it would translate into.
Legend:
settings.functionName = clickedOnItem
t.parentNode.id = IdofParent
JavaScript has an
eval
function that evaluates a string and executes it as code:Seeing as I hate eval, and I am not alone:
Edit: In reply to @Mahan's comment: In this particular case,
settings.functionName
would be"clickedOnItem"
. This would, at runtime translatevar fn = window[settings.functionName];
intovar fn = window["clickedOnItem"]
, which would obtain a reference tofunction clickedOnItem (nodeId) {}
. Once we have a reference to a function inside a variable, we can call this function by "calling the variable", i.e.fn(t.parentNode.id)
, which equalsclickedOnItem(t.parentNode.id)
, which was what the OP wanted.More full example:
If
settings.functionName
is already a function, you could do this:Otherwise this should also work if
settings.functionName
is just the name of the function:eval() is the function you need to do that, but I'd advise trying one of these things to minimize the use of eval. Hopefully one of them will make sense to you.
Store the function
Store the function as a function, not as a string, and use it as a function later. Where you actually store the function is up to you.
or
Store function name
Even if you have to store the function name as a string, you can minimize complexity by doing
which minimizes the amount of Javascript you have to construct and eval.
Dictionary of handlers
Put all of the action functions you might need into an object, and call them dictionary-style using the string.
(Minor note: If instead here you used syntax
itemActions[actionName](t.parentNode.id);
then the function would be called as a method ofitemActions
.)I prefer to use something like this:
Here is a more generic way to do the same, while supporting scopes :
Hope it can help some people out.