cocos2d-x lua 使用自定义消息EventCustom

cocos2d-x lua 使用自定义消息EventCustom

version: cocos2d-x 3.6

1.发送消息

-- post message
-- event将会被传递给消息接收函数,所以所有需要传递的数据都可放到event中
local event = cc.EventCustom:new("MSG_TEST")
event._usedata = {["state"]=self.curState, ["actionId"]=self.actionId}
cc.Director:getInstance():getEventDispatcher():dispatchEvent(event)

2.监听与接收

  • 监听消息需要调用self:enableNodeEvents()使消息接收有效
-- listener
local ActorSprite = class("ActorSprite", cc.Node)

function ActorSprite:initEventListener()
	self:enableNodeEvents()  -- cc.Node
	self.eventListeners = {} -- user to delete when dtor
	
	local listener = cc.EventListenerCustom:create(MSG_TEST, handler(self, self.onChangeState))
    local eventDispatcher = self:getEventDispatcher()
    eventDispatcher:addEventListenerWithFixedPriority(listener, 1)
    table.insert(self.eventListeners, listener)	
end

function DogSprite:onChangeState(event)
    local dogId = event._usedata["dogId"]
    local actionId = event._usedata["actionId"]
    local eventName = event:getEventName()
end

return ActorSprite

3.清理

  • 在ActorSprite被释放之后,需要将监听删除,否则收到消息后self为nil,将会导致异常(onCleanup将会在节点被删除时自动调用)。
function ActorSprite:onCleanup()  -- cc.Node
    for i, var in ipairs(self.eventListeners) do
        cc.Director:getInstance():getEventDispatcher():removeEventListener(var)
    end  
end
posted @ 2015-06-03 17:49  、拂晓  阅读(2931)  评论(0编辑  收藏  举报