Ricardo Quesada
unread,Jun 19, 2012, 2:36:54 PM6/19/12You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to dev-tech-...@lists.mozilla.org
Hi List,
I am working on adding Javascript support to cocos2d-iphone (a popular
Objective-C engine).
I created an script that parses Objective-C code and generates glue code
for Spidermonkey.
So far, it is working OK...
...but I have a doubt regarding how to handle Javascript callback functions
inside SpiderMonkey. In particular, I do not know how what is the best
strategy to "root" "orphan" functions.
* should I add it as a slot of "this" ?
* should I add it as a property of this ?
* If I add it in the "root", when should I remove it ?
Thank you,
Ricardo
Example:
// When the callback is an "orphan" function, and if the garbage collector
is
// called, then it will crash.
item.setCallback( function( sender )
{
cc.log("Clicked me from" + sender );
} );
// If the function was previously assigned to a property, then it will work
OK.
item.setCalback( item.callback );
On the "C" code, I have the following:
typedef void (^js_block)(id sender);
js_block jsval_to_block( JSContext *cx, jsval vp, JSObject *jsthis )
{
NSCAssert( JS_ValueToFunction(cx, vp ), @"Should be a function");
// HOW DO I "ROOT" vp ? Should I 'clone' it. I cannot use "vp" since it is
in the stack.
// Is there a way to know if "vp" is an "orphan" function ?
// If I "root" it, what is the best strategy to "unroot" it ?
// Is it a good practice to add it as an "slot" of the object ?
js_block block = ^(id sender) {
jsval rval;
JSObject *jsobj = get_or_create_jsobject_from_realobj( cx, sender );
jsval val = OBJECT_TO_JSVAL(jsobj);
// Will crash here if "vp" is orphan, and the GC is called before this
JS_CallFunctionValue(cx, jsthis, vp, 1, &val, &rval);
};
return [[block copy] autorelease];
}
JSBool JSPROXY_CCMenuItem_itemWithBlock__static(JSContext *cx, uint32_targc,
jsval *vp) {
...
jsval *argvp = JS_ARGV(cx,vp);
js_block arg0;
arg0 = jsval_to_block( cx, *argvp++, JS_THIS_OBJECT(cx, vp) );
...
return JS_TRUE;
}