如何在cocos2d-x中从c ++调用javascript函数

时间:2013-03-21 09:37:34

标签: javascript cocos2d-x

在我的cocos2d-x js项目中,我使用cxx-generator将c ++函数绑定到js,这样,我创建了一个ios alertView并将其显示为我的js代码,但是当用户按下OK按钮时,我可以通过现在js的事件,我试着用Google搜索了所有的2天,但我不能这样做,如果有人知道解决方案是什么,请帮助我,非常感谢!

3 个答案:

答案 0 :(得分:2)

你没有提供任何代码,所以很难给你特别的帮助,但是这样的事情应该提供一些方向:

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);
    }
}

然后,在你的JS文件中:

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);
  }
});

答案 1 :(得分:0)

请调用this._super();用ctor方法。

ctor: function()
{
    this._super();
    // The usual init stuff
    Poo.hello(this, "myCallback");
}

答案 2 :(得分:0)

这个答案不再适用于最新的Cocos2dx版本。 3.12没有“JS_GET_PROXY”......

我花了几天的时间试图弄清楚如何从C ++中调用JS函数,但没有用。因此,在一天结束时,我发现了一种通过创建自定义cc.nodes并使用已经实现的getter和setter函数在其字段中发送信息的方式来发送和接收两者之间的消息。

相关问题