Reputation: 3717
I am quite new to javascript, but I know you can call a function with it being represented by a string such that:
var function_to_call = window[values['function']];
//Where values['function']='functionName'
So far so good, then we have:
if(typeof function_to_call == 'function'){
if(values['parameters']!= '')
function_to_call(values['parameters']);
else function_to_call();
};
Of course, this won´t work because the parameters come out as "parameter1, parameter2" all in one string so you end up with
function_to_call("parameter1, parameter2");
rather than
function_to_call(parameter1, parameter2);
any ideas? Appreciate your time!
EXPANDED:
The parameters passed to the function represent the "id" of elements in the page; so the function that is called will be trying to get those elements by doing:
document.getElementById(parameter1);
...some other things...
document.getElementById(parameter2);
Upvotes: 1
Views: 2809
Reputation:
I assume the parameter names represent global variables as well.
If so, you could split them into an Array, then .map()
the Array into a new array of the related globals.
Then use .apply()
to invoke the function with the array of arguments.
if (typeof function_to_call == 'function') {
if(values['parameters']!= '') {
var args = values['parameters'].split(",")
.map(function(name) {
return window[name.trim()];
});
function_to_call.apply(window, args);
} else function_to_call();
}
The .trim()
and .map()
methods will need a shim for IE8... but this mainly shows how you could do it. As an alternative, you could pass a regex to .split()
to take care of any spaces.
var args = values['parameters'].split(/\s*,\s*/)...
Upvotes: 3
Reputation: 298
if(typeof function_to_call == 'function'){
if(values['parameters']!= '')
setTimeout('function_to_call('.values['parameters'].');');
else setTimeout('function_to_call();',0);
}
Upvotes: 0