Reputation: 2010
I'm trying to send a Javascript function object to Objective-C via JavascriptCore, leveraging the JSExport protocol. I have a function declared in Objective-C, conforming to JSExport as follows:
(class View)
+ (void) newWithFunc:(id)func
{
NSLog(@" %@ ", func);
}
After declaring this class, I try to call the function above with a Javascript function object as a parameter
JSValue *val;
val = [context evaluateScript:@"var mufunc = function() { self.value = 10; };"];
val = [context evaluateScript:@"mufunc;"];
NSLog(@" %@", val); //Prints as 'function() { self.value = 10; }', seems correct.
val = [context evaluateScript:@"var view = View.newWithFunc(mufunc);"];
When the last call is made, the parameter sent to my Objective-C method is of type 'NSDictionary', which doesn't seem very valuable if what I would like to do is call that function from Objective-C at a later point in time. Is this possible with JavascriptCore?
Upvotes: 3
Views: 563
Reputation: 36
Please mark Tayschrenn's answer as correct. I don't know how he knew this or where it's documented, but this is what I figured out by trial and error:
- (void)newWithFunc: (JSValue*)func
{
[func callWithArguments:@[]]; // will invoke js func with no params
}
Declaring the parameter (id)func
apparently causes the javascript-cocoa bridge to convert it to an NSDictionary (as you noticed), rendering it unusable as a callable JSValue.
Upvotes: 1
Reputation: 1212
This is definitely possible, but you need to change newWithFunc: to accept a JSValue* rather than plain id. The reason is that JSValue* is a special type for JavaScriptCore - it won't try to convert the JS value to its native equivalent but rather wrap it in a JSValue and pass it on.
Upvotes: 1