tags:

views:

201

answers:

3

Suppose I have a javascript function of the form:

function(){alert("blah");}

Suppose I also have an applet, which has a method called doStuff that takes the function as a parameter:

MyApplet.doStuff(function(){alert("blah");});

Now suppose that the applet passes the function to a success or failure javascript callback function depending on the result of its calculations. In that callback function, I want to execute the function so that the user gets my exceedingly informative "blah" message:

function callback(func) {
  func();
}

However, in the example above, func is no longer considered to be of type "function" (typeof func will return "object"). Is it possible to convert func to be a function so that it can be executed? I have a number of hacks in mind that can give me what I want, but they are very ugly and I was hoping that I was missing something simple.

Any help is greatly appreciated.

+1  A: 

Try func.call()

Upper Stage
If that works, then `typeof func` would be `"function"`, not `"object"` as in the OPs scenario.
Crescent Fresh
I tried both func.call() and func.apply() and neither worked.
Hypnotic Meat
Have you stepped through the code with FireBug (or some other debugger)? Your statement above suggests your function should not be converted to an object; it might be enlightening to know exactly when this function ceases being a function.
Upper Stage
The function is getting converted when the JSObject.call() method triggers. It takes an array of Objects representing the parameters to the callback function.
Hypnotic Meat
So, if your JSObject was func, then the framework would call your func?How about rather than passing a func to doStuff, you pass an object that includes func? And then call obj.func()?
Upper Stage
+2  A: 

Using the same style code as you already have, the following should alert "called!":

function callback(func){
  func();
}
callback(function(){
  alert("called!");
});

Is MyApplet.doStuff(function(){alert("blah");}); definitely passing its argument to the callback function unchanged?

JamesAlmond
Yes, from the applet to the callback function, the argument is unchanged in terms of content. The only change is that now javascript interprets it as an object rather than a function.
Hypnotic Meat
A: 

I opted to go for a different solution that isn't as ugly as I imagined it would be. The JSObject.call() java method converts all the callback function parameters to plain jane objects. So instead of passing:

function(){alert("blah")}

I now pass:

alert("blah")

or after some annoying escaping:

''alert(\''blah\'');''

Not so terrible eh? Many thanks to everyone that offered their help, it is appreciated. But, just out of curiosity, does anyone know off the top of their head if it's possible to pass something from java to a javascript function via JSObject so that it retains its "function" type?

Hypnotic Meat