views:

120

answers:

3

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
}
+1  A: 

Try this:

 options.onSuccess = eval('function() {alert(\'test\')}');
 options.onSuccess(otherObject);
cloudhead
Isn't this the same as: eval('function() {alert(\'test\')}')(otherObject);
Ropstah
As Itay notes, you'll want to parenthesize the parameter to eval('(' + options.onSuccess + ')') - otherwise, FF will choke. Sorry, forgot about that...
Shog9
+5  A: 

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:

<a onclick="handleClick(this, {onSuccess : function(obj) { alert(obj) }}, 'test');">
  Click
</a>

...

function handleClick(element, options, otherObject) {
    options.onSuccess(otherObject); // works...
}

But if you really want to do it your way, then cloudhead's solution will do just fine.

Shog9
bah... and here I was in the middle of writing my exposition on the scope of eval. +1 for answering the real question.
Jimmy
Yeah I ended up doing this, but this means I can't use the json_encode in PHP anymore... this encapsulates everything in strings..
Ropstah
@ropstah: not sure why you're trying to pass function definitions down via JSON... Unless you're actually generating these functions on the fly, server-side, you may want to consider putting together a library of functions and then just *naming* them in the JSON. You can then look up the function you want without bothering with eval()
Shog9
Great comment, I will actually do this
Ropstah
A: 

It only worked on my FF when I added an assignmnet into a dummy variable:

 options.onSuccess = 'dummyVariable = function(x) {alert("x=" + x);}';
 f = eval(options.onSuccess);
 f(5);
Itay
Heh, good catch. But rather than introducing dummyVariable, you can just wrap the value in parentheses.
Shog9