My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
YourOwnObjectsInJSCocoa  
Updated Feb 4, 2010 by parman...@gmail.com

Here's how to programmatically define your objects in JSCocoa's global scope, just like Safari's window, document, setTimeout.

Setting ObjC objects

  • setObject:withName:
  • removeObjectWithName:

These act like setValue:forKey:, setting and removing ObjC objects in the Javascript global scope.









You should no longer need what follows, but here goes anyway :

Internals and set on demand

You can set variables on the global object or create them on request. This is not JSCocoa specific stuff, straight JavascriptCore.

Creating a number named myVar in the global object

	JSStringRef jsName = JSStringCreateWithUTF8CString("myVar");
	JSObjectSetProperty(ctx, JSContextGetGlobalObject(ctx), jsName, JSValueMakeNumber(ctx, 1.2345), 0, NULL);
	JSStringRelease(jsName);					

Creating on request a number named myVar2

JSCocoa uses a callback named OSXObject_getProperty that JavascriptCore will call when requesting a global variable. You can hook there :

JSValueRef OSXObject_getProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyNameJS, JSValueRef* exception)
{
	NSString*	propertyName = (NSString*)JSStringCopyCFString(kCFAllocatorDefault, propertyNameJS);
	[propertyName autorelease];
	
	if ([propertyName isEqualToString:@"myVar2"])	return	JSValueMakeNumber(ctx, 7.89);

To return an ObjC object, box it in a Javascript object :

	MyObject* myObject = ...get an ObjC object here...
	JSObjectRef jsObject = [JSCocoaController jsCocoaPrivateObjectInContext:ctx];
	JSCocoaPrivateObject* private = JSObjectGetPrivate(jsObject);
	private.type = @"@";
	[private setObject:myObject];

Sign in to add a comment
Powered by Google Project Hosting