Passing a Javascript callback to Objective-C

298 views
Skip to first unread message

Ian Beck

unread,
Sep 8, 2010, 2:28:45 PM9/8/10
to JSCocoa
I'm having trouble passing a Javascript callback function to an
Objective-C method. Here's an example of the code that I'm running:

JAVASCRIPT
var callbackFunction = function(dictionary) {
log('Working!');
};

var testCallback = function(objcObject) {
objcObject.invokeJSCallback(callbackFunction);
};

OBJECTIVE-C
@implementation MyClass

// Loads up JSCocoa and calls the testCallback function:
// [jsc callJSFunctionNamed:@"testCallback" withArguments:self, nil];

- (void) invokeJSCallback:(JSValueRef)callbackFunction {
// Here's where I want to invoke the callbackFunction to send
control back to Javascript
}

@end

Initially, I was getting all sorts of segfaults when I tried to do
anything with callbackFunction in Objective-C, so out of curiosity I
switched its type to "id", and sure enough I was getting an Obj-C
object rather than a JSValueRef as I'd expected. When I checked
[callbackFunction className] I got "NSCFDictionary", and when I tested
its contents it turns up empty.

What am I doing wrong? I can't figure out why I'm getting an empty
dictionary passed back instead of some form of reference to the
Javascript function that I passed in on the other side of the bridge.
Ideally what I want to do is convert the callbackFunction into a
JSValueRef so that I can do something like [jsc
callJSFunction:callbackFunction withArguments:args].

Thanks for any insight you can offer!

Ian

Patrick Geiller

unread,
Sep 8, 2010, 3:18:12 PM9/8/10
to jsc...@googlegroups.com

You can't use (JSValueRef) to move functions around as they are dependent on a specific context.
Instead, use (JSValueRefAndContextRef) - it's special cased to move raw JS values to ObjC.

- (void) invokeJSCallback:(JSValueRefAndContextRef)callbackFunction {
// Get JSCocoa controller from JSContextRef
id jsc = [JSCocoa controllerFromContext:valueAndContext.ctx];
// Call
[jsc callJSFunction:valueAndContext.value withArguments:[NSArray arrayWithObjects:..., nil]];
}

-Patrick

> --
> JSCocoa: http://inexdo.com/JSCocoa
> Source: http://github.com/parmanoir/jscocoa/tree/master
> Docs: http://code.google.com/p/jscocoa/
> Group: http://groups.google.com/group/jscocoa
> Unsubscribe: jscocoa+u...@googlegroups.com

Ian Beck

unread,
Sep 8, 2010, 4:50:32 PM9/8/10
to JSCocoa
Thanks, Patrick! That was exactly the problem that I was having, and
it's now working perfectly.

Ian
Reply all
Reply to author
Forward
0 new messages