How to call js functions in c++ class

I am trying to use ios alertView in cocos2d-x js project, I write a c*+ class and bind it to js code, In js I call it like this :
var alert = new cc.AlertView; alert.initWithTitle("Message", "Body", "OK"); alert.show();
It works fine.
But when user clicks OK button, I want to pass the event from c*+ to js. How can I implement this? thx

You could use ScriptingCore::executeFunctionWithOwner to invoke a js function.

James Chen wrote:

You could use ScriptingCore::executeFunctionWithOwner to invoke a js function.

Is there a convenient function to get Owner? thx

You could use “JS_GET_PROXY” to get a js object by a native object.

dear dumganhar
I am new to cocos2d-x jsb, and I am facing the same problem as gutaideng
here is my code in c++:

void cToJs::call(void) {

ScriptingCore* sc =ScriptingCore::getInstance();

jsval nsval;
    if(!sc){
        CCLog(“sc is NULL”);
    }
    if(!sc->getGlobalContext())
    {
        CCLog(“sc->getGlobalContext() is NULL”);
    }
    if(!sc->getGlobalObject())
    {
        CCLog(“sc->getGlobalObject is NULL”);
    }
    JS_GetProperty(sc->getGlobalContext(), sc->getGlobalObject(),“msgFromC”, &nsval);
    if (nsval !=JSVAL_VOID) {
        sc->executeFunctionWithOwner(nsval,“call”);
        CCLog(“js function excuted”);
    }else{
        CCLog(“can not find js class”);
    }
}

and here is my js code:

var msgFromC = cc.Node.extend({
  ctor: function() {
    this._super();
  },
  call: function(msg) {
    cc.log("I got a message back from C++: " + msg);
  }
});

when I invoke:
cToJs *p = new cToJs();
p->call();

the log shows:

D/cocos2d-x debug info(18621): sc->getGlobalContext() is NULL
D/cocos2d-x debug info(18621): sc->getGlobalObject is NULL
A/libc(18621): Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1), thread 18621

what’s wrong with it?

Was your ScriptingCore started? It seemed not.

Please make sure ScriptingCore::getInstance()->start() is invoked before executing your code.
start is normally invoked in AppDelegate::applicationDidFinishLaunching, you could refer to js-tests.

1 Like

new version, new style
what about version 3.11?