上一篇,寫了個CCPomelo導出到js,一直研究怎麼寫回調,研究了半天也沒找到哪裏能夠自動生成代碼了,看了半天源碼,只好手動添加代碼,在自動生成的 中修改 函數
CCPomelo增長几個成員 ui
class CCPomelo : public cocos2d::CCObject
{
public:
CCPomelo(){};
~CCPomelo(){}; this
int connect(const char* addr, unsigned short port); 指針
int request(const char* route, const char* msg); 對象
virtual void onRequestCallback(int status, const char* msg); get
void log(const char* pszLog); 回調函數
static CCPomelo* getInstance();
JSContext *m_jsCx;
JSObject *m_jsThisObj;
jsval m_jsFun;
jsval *m_jsArgv;
protected:
void* m_client; 源碼
protected:
static CCPomelo* m_pInstance;
}; string
JSBool js_cocos2dx_extension_CCPomelo_request(JSContext *cx, uint32_t argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
JSBool ok = JS_TRUE;
JSObject *obj = JS_THIS_OBJECT(cx, vp);
js_proxy_t *proxy; JS_GET_NATIVE_PROXY(proxy, obj);
CCPomelo* cobj = (CCPomelo *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, JS_FALSE, "Invalid Native Object");
if (argc == 3) {
const char* arg0;
const char* arg1;
jsval arg2;
std::string arg0_tmp; ok &= jsval_to_std_string(cx, argv[0], &arg0_tmp); arg0 = arg0_tmp.c_str();
std::string arg1_tmp; ok &= jsval_to_std_string(cx, argv[1], &arg1_tmp); arg1 = arg1_tmp.c_str();
//************添加的部分 io
cobj->m_jsCx = cx;//js上下文
cobj->m_jsThisObj = obj;//js對象指針
cobj->m_jsFun = argv[2];//回調函數
//************結束
JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments");
int ret = cobj->request(arg0, arg1);
jsval jsret;
jsret = int32_to_jsval(cx, ret);
JS_SET_RVAL(cx, vp, jsret);
return JS_TRUE;
}
JS_ReportError(cx, "wrong number of arguments: %d, was expecting %d", argc, 3);
return JS_FALSE;
}
在CALLBACK裏面調用JS函數
void CCPomelo::onRequestCallback(int status, const char* msg)
JS代碼:
cc.Pomelo.getInstance().connect("127.0.0.1", 3010);
cc.Pomelo.getInstance().request("connector.helloHandler.hi", "{'msg' : 'hi~'}".replace(/'/g,"\""), this.onCallback);
onCallback: function () { cc.Pomelo.getInstance().log("Pomelo onCallback"); },