How can I have a parameter to one JS function be Function Name with parameters to call another function?
something like:
onClick="Clicked(this, 'SomeFunction('test')'"
Regards
onClick = "Clicked(this, function () {SomeFunction('test')});"
function Clicked (obj, functionToFire)
{
functionToFire();
}
<span onclick="Clicked(this, 'SomeFunc', ['test', 123])">AAAA</span>
...
function Clicked(thisObject, funcName, params)
{
// find an object with name funcName in default (window) scope
var func = window[funcName];
// test that the object exist and that it's a function
if (func && typeof func == "function")
{
// call the function with passed params
// passing 'thisObject' enables to use 'this' keyword within the called function
func.apply(thisObject, params);
// as an alternative you may call it without 'this' object
func.apply(null, params);
}
}
function SomeFunc(text, num)
{
alert("text: " + text + ", number: " + num);
}
<script>
function doSomeWork(arg1, arg2)
{
arg2();
}
function displayThis(msg)
{
alert(msg);
}
doSomeWork("11",function(){ displayThis("123");});
</script>
arg2(arg1);What you have would work, although, you'd need to use the javascript eval function to evaluate the value once in the function:
function Clicked(obj, functionText)
{
// do something with object....
eval(functionText);
}
Otherwise, if there's no parameter, you can always pass the function itself:
onClick="Clicked(this, SomeFunction)"
and implement like this:
function Clicked(obj, func)
{
// do something with object...
func();
}
eval for something like this. eval has it's use(s?), this isn't one of them.