[cocos2dx_lua]Lua版自定义事件分发系统


--事件系统
----------------------------------
local EventSystem = class("EventSystem")
function EventSystem:ctor()
    self._eventBus = {}
end

-- _eventBus[eventName][tag] = listener
function EventSystem:regEvent(eventName,listener,tag)
    print(eventName,listener,tag)
    if type(eventName) == "string" and type(listener) == "function" then
        if not self._eventBus[eventName] then self._eventBus[eventName] = {} end
        tag = tag .. ''
        self._eventBus[eventName][tag] = listener
        printf("[[通知中心 %s 注册 %s 成功! ]]", eventName, tag)
    else
        printf("[[通知中心 %s 注册 %s 失败! ]]", tostring(eventName),tag .. '')
    end
end


function EventSystem:postEvent(eventName,data)
    assert(eventName, "EventSystem:postEvent eventName = nil")
    local target = self._eventBus[eventName]
    if not target then printf("[[通知中心 %s 不存在! ]]", eventName) return end

    local event = { eventName = eventName, tag = nil, data = data }
    if target then
        for _tag,v in pairs(target) do
            printf("[[通知中心 向 %s 发送 %s 成功! ]]", _tag, event.eventName)
            event.tag = _tag
            v( event )
        end
    end
end

function EventSystem:unRegEvent(eventName,tag)
    if self._eventBus[eventName] then
        tag = tag .. ''
        self._eventBus[eventName][tag] = nil
        printf("[[通知中心 %s 注销 %s 成功! ]]", eventName, tag)
    else
        printf("[[通知中心 %s 注销 %s 失败! ]]", eventName, tag)
    end
end

function EventSystem:unRegEventByName(eventName)
    if self._eventBus[eventName] then
        self._eventBus[eventName] = nil
        printf("[[通知中心 %s 注销成功! ]]", eventName)
    else
        printf("[[通知中心 %s 注销失败! ]]", eventName)
    end
end


function EventSystem:hasEventListenerByName(eventName)
    local t = self._eventBus[eventName]
    if not t then return false end
    for _,__ in pairs(t) do
        return true
    end
    return false
end

function EventSystem:hasEventListener(eventName,tag)
    return (not self._eventBus[eventName][tag .. ''])
end

function EventSystem:removeAllEventListeners()
    self._eventBus = {}
end

function EventSystem:dumpAllEventListeners()
    print("---- EventSystem:dumpAllEventListeners() ----begin")
    for name, listeners in pairs(self._eventBus) do
        printf("-- event: %s", name)
        for tag, listener in pairs(listeners) do
            printf("--     tag: %s, listener: %s", tostring(tag), tostring(listener))
        end
    end
    print("---- EventSystem:dumpAllEventListeners() ----end")
end

return EventSystem

[设计模式]Observer观察者模式

你可能感兴趣的:(Cocos2dx)