I have the following situation in JavaScript:
<a onclick="handleClick(this, {onSuccess : 'function() { alert(\'test\') }'});">Click</a>
The handleClick function receives the second argument as a object with a onSuccess property containing the function definition…
How do I call the onSuccess function (which is stored as string) -and- pass otherObject to that function? (jQuery solution also fine…)?
This is what I’ve tried so far…
function handleClick(element, options, otherObject) {
options.onSuccess = 'function() {alert(\'test\')}';
options.onSuccess(otherObject); //DOES NOT WORK
eval(options.onSuccess)(otherObject); //DOES NOT WORK
}
You really don’t need to do this. Pass the function around as a string, i mean. JavaScript functions are first-class objects, and can be passed around directly:
…
But if you really want to do it your way, then cloudhead’s solution will do just fine.