【已解决】cocos2dx lua中如何实现自定义事件呢?

1、能否在lua和C++中相互监听彼此的自定义事件?
2、lua中如何创建自定义的事件?cc.EventCustom貌似没有创建的方法。

难道没人会?

监听:
local eventDispatcher = self:getEventDispatcher()
local listener = nil

local function handleBuyGoods(event) 
    cclog("handleBuyGoods")
end
listener = cc.EventListenerCustom:create("HandleKey.kDidBuyGoods", handleBuyGoods)
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)

广播:
local eventDispatcher = cc.Director:getInstance():getEventDispatcher()
local event = cc.EventCustom:new(“HandleKey.kDidBuyGoods”)
eventDispatcher:dispatchEvent(event)

谢谢你,我测试一下

原来是我的代码里
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
把最后的self给漏掉了。 :12:


另外cc.EventCustom:new,这里的new方法在哪里定义的?cocos2dx的lua源码里也没有翻到啊?

如何传递参数呢?lua里不能像C++那样用getUserData来获取传递的参数啊

请参考lua-tests中NewEventDispatcherTest.lua的CustomEventTest测试例。

local function handleBuyGoods(event)
cclog(“handleBuyGoods”)

end

这个函数里面的event就是广播的event的lua对象
local event = cc.EventCustom:new(“HandleKey.kDidBuyGoods”)

然后,你给这个lua对象随便定义属性就行:event.随便属性 = “随便属性”

谢谢您!这样是在lua间可以传递参数了。我想在lua和C++间通过事件传递参数,看了下源码,感觉比较困难。因为参数的类型不好确定。在进行lua和C++转换的时候,就很不灵活了,除非针对每种要传递的类型,单独地写方法来进行转换。

— Begin quote from ____

引用第8楼ntsjun于2014-11-22 22:20发表的 回 7楼(imyp2635) 的帖子 :
谢谢您!这样是在lua间可以传递参数了。我想在lua和C++间通过事件传递参数,看了下源码,感觉比较困难。因为参数的类型不好确定。在进行lua和C++转换的时候,就很不灵活了,除非针对每种要传递的类型,单独地写方法来进行转换。 http://www.cocoachina.com/bbs/job.php?action=topost&tid=238132&pid=1179116

— End quote

C++调用LUA函数,可使用ScriptHandlerMgr,参考这帖子:
http://blog.sina.com.cn/s/blog_93add5520101lv02.html

mark…mark