问题
In my cocos2d-x js project, I bind c++ functions to js using cxx-generator, in this way, I create an ios alertView and show it form my js code, but when user press OK button, I can pass the event to js now, I tried and googled all the 2 days, but I can not do it, if anyone knows what the solution is, please help me, thanks very very much!
回答1:
You didn't provide any code, so it's hard to give you specific help, but something like this should provide some direction:
Poo.h
class JSObject;
class Poo : cocos2d::CCNode {
public:
static void hello(JSObject *target, std::string selector);
}
Poo.cpp
Poo::hello(JSObject *target, std::string selector) {
if (target) {
js_proxy_t * p;
JS_GET_PROXY(p, target);
if (!p) {
return;
}
jsval retval;
jsval dataVal = std_string_to_jsval(ScriptingCore::getInstance()->getGlobalContext(), "Hello World");
ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(p->obj), selector.c_str(), 1, &dataVal, &retval);
}
}
Then, in your JS file:
var Demo = cc.Node.extend({
ctor: function() {
this._super();
// The usual init stuff
Poo.hello(this, "myCallback");
},
myCallback: function(msg) {
cc.log("I got a message back from C++: " + msg);
}
});
回答2:
Please invoke this._super(); in ctor method.
ctor: function()
{
this._super();
// The usual init stuff
Poo.hello(this, "myCallback");
}
回答3:
This answer does not work anymore with latest Cocos2dx versions. 3.12 does not have "JS_GET_PROXY"...
I spent several days trying to figure out how to fire a call to a JS function from C++, with no avail. So at the end of the day I found a hacky way to send and receive messages between the two, by creating custom cc.nodes and using already implemented getter and setter functions to send information in their fields.
来源:https://stackoverflow.com/questions/15543840/how-to-call-javascript-function-from-c-in-cocos2d-x