日常工作中经常会用到触发机制,这里就提供一个注册触发机制,在代码中在也不用专门去调用各个模块的接口;只需要触发即可,触发后会自动调用接口
直接上代码
local _EventHandle = {};
_EventHandle.listenerHandleIndex = 0
_EventHandle.listenersList = {}function _EventHandle:AddEventListener(eventName, listener)eventName = string.upper(eventName);if self.listenersList[eventName] == nil thenself.listenersList[eventName] = {};endself.listenerHandleIndex = self.listenerHandleIndex + 1;self.listenersList[eventName][self.listenerHandleIndex] = listener;return self.listenerHandleIndex;
endfunction _EventHandle:dispatchEvent(event)event.name = string.upper(event.name);local _eventName = event.name;if self.listenersList[_eventName] == nil then return; endfor _index, _listener in pairs(self.listenersList[_eventName]) dolocal ok, _ret = Try(_listener, event)if not ok thenG_logger:warn_format("[_EventHandle:dispatchEvent] Failed, event:%s, err:%s", _eventName, tostring(_ret))elseif _ret == "__REMOVE__" thenself.listenersList[_eventName][_index] = nil;endend
endfunction _EventHandle:removeEventListener(eventName, key)eventName = string.upper(eventName);if self.listenersList[eventName] == nil then return; endfor _index, _listener in pairs(self.listenersList[eventName]) doif key == _index or key == _listener thenself.listenersList[eventName][_index] = nil;break;endend
endfunction _EventHandle:removeAllEventListenersForEvent(eventName)self.listenersList[string.upper(eventName)] = nil;
endfunction _EventHandle:removeAllEventListeners()self.listenersList = {};
endreturn _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})