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 tha开发者_Python百科t the method is not defined :
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?
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');};
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 + ")()" )
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();
...
}
}
精彩评论