Lua监听事件观察者模式(多个监听者监听)
fireEvent 产生事件,创建协程分发(在registerEventListener注册过的事件中通过事件名字找到对应的信息,然后执行对应模块的OnEvent函数),多个地方都注册了同一个事件的话,则所有监视该事件的模块都会收到
1 -- 事件ID 2 -- 可配置与配置表中(TODO) 3 activity_manager.activityEventId = {} 4 activity_manager.activityEventId.EVENT_TEST = 1; 5 6 -- 事件表 7 local event_tb = {}
1 function activity_manager:registerEventListener(layerName, eventId, func) 2 if type(eventId) ~= "number" then 3 print('ROORR:: activityEventId 参数非法') 4 return 5 end 6 7 if event_tb[eventId] ~= nil then 8 local _samelayer = false 9 for k, v in pairs(event_tb[eventId].monitor) do 10 if v.layerName == layerName then 11 print('WARNING:: eventId和layerName都一样前面的注册信息会被覆盖', eventId, layer) 12 _samelayer = true 13 v.func = func 14 end 15 end 16 if not _samelayer then 17 local _monitor = {} 18 _monitor.layerName = layerName 19 _monitor.func = func 20 table.insert(event_tb[eventId].monitor, _monitor) 21 end 22 else 23 event_tb[eventId] = {} 24 event_tb[eventId].monitor = {} 25 local _monitor = {} 26 _monitor.layerName = layerName 27 _monitor.func = func 28 table.insert(event_tb[eventId].monitor, _monitor) 29 end 30 end
1 function activity_manager:releaseEventListener(layerName, eventId) 2 for v in pairs(event_tb[eventId].monitor) do 3 if v.layerName == layerName then 4 v = nil 5 end 6 end 7 end
1 function activity_manager:dispatchEvent(eventId, args) 2 if type(eventId) ~= "number" then 3 print('ROORR:: activityEventId 参数非法') 4 return 5 end 6 7 if event_tb[eventId] == nil then 8 print('ROORR:: activityEventId 参数不存在') 9 return 10 end 11 12 for k, v in pairs(event_tb[eventId].monitor) do 13 local func = v.func 14 local layerName = v.layerName 15 func(args) 16 end 17 end
1 function activity_manager:fireEvent(eventId, args) 2 if not event_tb or not next(event_tb) then return end 3 local co = coroutine.create( function(eventId, args) 4 self:dispatchEvent(eventId, args) 5 end) 6 7 local status, msg = coroutine.resume(co, eventId, args) 8 assert(status, msg) 9 end
1 function activity_manager:releaseEventListenerByName(layerName) 2 for k, v in pairs(event_tb) do 3 for index, _monitor in pairs(v.monitor) do 4 if _monitor.layerName == layerName then 5 v.monitor[index] = nil 6 end 7 end 8 end 9 end
祝我无坚不摧,祝我百毒不侵,祝我狼心狗肺,祝我逍遥快活。