Lua 事件系统

要求:实现事件的监听、移除、派发

local EventSystem = {}
local this = EventSystem
this.mEventTable = {}
this.mObjTable = {}


--注册事件
function EventSystem:AddListener(eventName, handler, obj)
    
    if eventName == nil or (type(eventName) ~= 'string') and (type(eventName) ~= 'number') then
        print('EventSystem::AddListener -> eventName must be string or number')
    end

    if handler == nil or (type(handler) ~= 'function') then
        print('EventSystem::AddListener -> handler must be funciton')
    end

    this.mObjTable[obj] = this.mObjTable[obj] or {}

    table.insert(this.mObjTable[obj], {eventName, handler})
 

    this.mEventTable[eventName] = this.mEventTable[eventName] or {}

    table.insert(this.mEventTable[eventName], handler)

end


--移除事件
function EventSystem:RemoveListener(eventName, handler)
    --print('EventSystem::RemoveListener')
    --print(eventName, handler)
    if not eventName or not this.mEventTable[eventName] then
        print('EventSystem::RemoveListener -> Can\'t find eventName'..eventName)
        return
    end

    for k, v in pairs(this.mEventTable[eventName]) do
     
        if v == handler then
           table.remove(this.mEventTable[eventName], k)
        end
    end

end


--派发消息
function EventSystem:Dispatch(event)
    print('EventSystem::Dispatch '.. event)
   
    if not event or  this.mEventTable[event] == nil then
        return
    end

    for k, v in pairs(this.mEventTable[event]) do
        v()
    end

end

-- 移除对象对应的监听
function EventSystem:RemoveObjectListeners(Obj)
    if not Obj or not this.mObjTable[Obj] then
        return
    end

    for k, v in pairs(this.mObjTable[Obj]) do
       
        EventSystem:RemoveListener(v[1], v[2])

    end

    this.mObjTable[Obj] = nil

end

return EventSystem
上一篇:2


下一篇:lua_State数据结构