Patrick Desjardins
Patrick Desjardins

Reputation: 141023

Javascript passing function into parameter?

I use the JQuery dialog and from the PHP I can build some add-in to the button. To be able to add code from the server side I pass a method by parameter. The problem is that FireBug tell me that the method is not defined :

alt text

okHandler is the parameter of this method call to raise the dialog and it contain a simple alert message for the moment, later some Ajax calls. Any idea why it doesn't work?

alt text

Upvotes: 1

Views: 478

Answers (3)

Drew Wills
Drew Wills

Reputation: 8446

Is the okHandler() function loaded (as a valid JS object -- not a String) at the time you get that error?

I believe it's not alright to call something like "if (foo != null)" if foo hasn't already been declared as a variable somewhere. FireBug would complain: "okHandler is no defined."

Try something like this...

var myHandlers = {};
// Load okHandler as a member of myHandlers when applicable here...
$('#dialog'+idbox)...
    "Oky": function() {
        myHandlers.okHandler && myHandlers.okHandler();
        ...
    }
}

Upvotes: 0

Shog9
Shog9

Reputation: 159718

As John Kugelman notes, okHandler appears to be a string. It would work better if it was a function... However, if a string it must be, then you'll need to pass it through eval() to actually execute it:

eval( "(" + okHandler + ")()" )

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 362187

It looks like okHandler is a string containing a function declaration, not an actual function? You have

okHandler = "function anonymous(){alert('This is a test');}";

instead of

okHandler = function(){alert('This is a test');};

Upvotes: 4

Related Questions