Android Back Button

Is there a way to set a callback for the Android back button in javascript? I’ve found how to do this in C++ but is this bound in javascript too?

Thanks,

— Joel

Was able to get this working by implementing ScriptingCore::executeLayerKeypadEvent in ScriptingCore.cpp. My code looks like this:

int ScriptingCore::executeLayerKeypadEvent(CCLayer* pLayer, int eventType)
{
    jsval value = int32_to_jsval(this->getGlobalContext(), eventType);
    JS_AddValueRoot(this->getGlobalContext(), &value);

    js_proxy_t * p;
    JS_GET_PROXY(p, pLayer);

    jsval retval;
    executeJSFunctionWithName(this->cx_, p->obj, "onKeypad", value, retval);


    JS_RemoveValueRoot(this->getGlobalContext(), &value);
    return 1;
}

My Javascript code looks like this:

var MyLayer = cc.Layer.extend({
    ctor: function() {
        this._super();
        cc.associateWithNative(this, cc.Layer);
        this.init();
    },

    init: function() {
        this.setKeypadEnabled(true);
        this.registerScriptKeypadHandler(1);
    },

    onKeypad:function(eventType) {
        if(eventType == 1) { // back button
            log("back button pressed");
        }
    },
});

Cheers,

— Joel

1 Like

How to do it with CocosBuilder and JSBindings?

Ok, the solution for CocosBuilder and JSB is here: http://www.cocos2d-x.org/boards/20/topics/30916?r=30958

I am using Cocos2dx JS 3.0 Final and changed the above code, since it threw some errors… But I have no idea what changes I have done in ScriptingCore… But I couldn’t make a JS handler to the back event…

Here is my code…

ScriptingCore.h:

int executeLayerKeypadEvent(cocos2d::CCLayer* pLayer, int eventType);

ScriptingCore.cpp:

int ScriptingCore::executeLayerKeypadEvent(cocos2d::CCLayer* pLayer, int eventType) {
jsval value = int32_to_jsval(this->getGlobalContext(), eventType);
JS_AddValueRoot(this->getGlobalContext(), &value);

js_proxy_t * p;
JS_GET_PROXY(p, pLayer);

jsval retval[2];
//executeJSFunctionWithName(this->_cx, p->obj, "onKeypad", value, retval);
executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), "onKeypad", 1, retval);

JS_RemoveValueRoot(this->getGlobalContext(), &value);
return 1;
}

in my Layer’s ctor:

    if( cc.sys.os == cc.sys.OS_ANDROID) {
        cc.associateWithNative(this, cc.Layer);
        this.setKeypadEnabled(true);
        this.registerScriptKeypadHandler(1);
    }

The layer is not rendered and the back button is also not working… Any help ??