luaオブザーバモード--イベント配布器実装

8063 ワード

 1 --EventDispatcher.lua
 2 local EventDispatcher = {}
 3 EventDispatcher.__index = EventDispatcher
 4 function EventDispatcher:new()
 5     local store = nil
 6 
 7     return function(self)
 8         if store then return store end
 9         local o =  {}
10         setmetatable(o, self)
11         self.__index = self
12         store = o
13         self.m_listeners = {}
14         return o
15     end
16 end
17 
18 EventDispatcher.instance = EventDispatcher:new()
19 
20 function EventDispatcher:addEvent(name,listener)
21     --          
22     local index = 1
23     if self.m_listeners[name] == nil then
24         self.m_listeners[name] = {}
25     else
26         local existIndex = self:getEventIndex(name,listener)
27         if existIndex ~= -1 then
28             return
29         end
30         index = #self.m_listeners[name] + 1
31     end
32     --cclog("EventDispatcher:addEvent %s,index = %d",name,index)
33     self.m_listeners[name][index] = listener
34 end
35 
36 function EventDispatcher:removeEvent(name,listener)
37     if self.m_listeners[name] == nil then
38         return
39     end
40     local existIndex = self:getEventIndex(name,listener)
41     if existIndex == -1 then return end
42     table.remove(self.m_listeners[name],existIndex)
43 end
44 
45 function EventDispatcher:dispatchEvent(name,...)
46     if self.m_listeners[name] == nil then
47         return
48     end
49     for k,v in pairs(self.m_listeners[name]) do
50         v(...)
51     end    
52 end
53 
54 function EventDispatcher:getEventIndex(name,listener)
55     if self.m_listeners[name] == nil then
56         return -1
57     end
58     for i=1,#self.m_listeners[name] do
59         if self.m_listeners[name][i] == listener then
60             return i
61         end
62     end
63     return -1
64 end
65 
66 return EventDispatcher

 
転載先:https://www.cnblogs.com/guoliangjun/p/6380617.html