日常工作中经常会用到触发机制,这里就提供一个注册触发机制,在代码中在也不用专门去调用各个模块的接口;只需要触发即可,触发后会自动调用接口
直接上代码
Lua
local _EventHandle = {};
_EventHandle.listenerHandleIndex = 0
_EventHandle.listenersList = {}
function _EventHandle:AddEventListener(eventName, listener)
eventName = string.upper(eventName);
if self.listenersList[eventName] == nil then
self.listenersList[eventName] = {};
end
self.listenerHandleIndex = self.listenerHandleIndex + 1;
self.listenersList[eventName][self.listenerHandleIndex] = listener;
return self.listenerHandleIndex;
end
function _EventHandle:dispatchEvent(event)
event.name = string.upper(event.name);
local _eventName = event.name;
if self.listenersList[_eventName] == nil then return; end
for _index, _listener in pairs(self.listenersList[_eventName]) do
local ok, _ret = Try(_listener, event)
if not ok then
G_logger:warn_format("[_EventHandle:dispatchEvent] Failed, event:%s, err:%s", _eventName, tostring(_ret))
elseif _ret == "__REMOVE__" then
self.listenersList[_eventName][_index] = nil;
end
end
end
function _EventHandle:removeEventListener(eventName, key)
eventName = string.upper(eventName);
if self.listenersList[eventName] == nil then return; end
for _index, _listener in pairs(self.listenersList[eventName]) do
if key == _index or key == _listener then
self.listenersList[eventName][_index] = nil;
break;
end
end
end
function _EventHandle:removeAllEventListenersForEvent(eventName)
self.listenersList[string.upper(eventName)] = nil;
end
function _EventHandle:removeAllEventListeners()
self.listenersList = {};
end
return _EventHandle;
AddEventListener:注册接口
dispatchEvent:触发接口
其他的接口都是移除接口
调用
注册:Event:AddEventListener("Event:try_unlock_idcard", __on_event_try_unlock_idcard),__on_event_try_unlock_idcard是回调函数
触发:Event:dispatchEvent({name = "Event:try_unlock_idcard", player = avatar_part.owner, data_type = HotPot_Type.flash_avatar_part_count, value = avatar_part.flash_count})