2013-03-21 22 views
-2

在我的cocos2d-x js項目中,我使用cxx生成器將C++函數綁定到js,通過這種方式,我創建了一個ios alertView並將其顯示爲我的js代碼,但是當用戶按下確定按鈕時,我現在可以將事件傳遞給js,我試了兩天,但是我做不到,如果有人知道解決方案是什麼,請幫助我,非常感謝!如何從C++中調用javascript函數cocos2d-x

+0

你應該在你的問題中增加更多代碼,這裏沒有任何答案。 – WeeklyDad 2013-03-21 09:45:51

回答

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

請調用this._super();採用ctor方法。

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

嗨,歡迎來到Stack Overflow!您可能需要添加更多關於它的解釋,以便與其他人更相關,並且清楚它的作用。 – 2013-06-26 05:29:16

0

此答案不再適用於最新的Cocos2dx版本。 3.12沒有「JS_GET_PROXY」...

我花了好幾天的時間試圖找出如何從C++發起一個JS函數的調用,但沒有用。因此,在一天結束時,我發現了一種在兩者之間發送和接收消息的方法,通過創建自定義cc.nodes並使用已實現的getter和setter函數在其字段中發送信息。