Lua事件派发器

Lua事件派发器

简易实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
-- EventDispatcher class
EventDispatcher = {}
EventDispatcher.__index = EventDispatcher

function EventDispatcher.new()
local self = setmetatable({}, EventDispatcher)
self.listeners = {}
return self
end

function EventDispatcher:addEventListener(eventName, callback)
if not self.listeners[eventName] then
self.listeners[eventName] = {}
end
table.insert(self.listeners[eventName], callback)
end

function EventDispatcher:removeEventListener(eventName, callback)
local eventListeners = self.listeners[eventName]
if eventListeners then
for i = #eventListeners, 1, -1 do
if eventListeners[i] == callback then
table.remove(eventListeners, i)
break
end
end
end
end

function EventDispatcher:dispatchEvent(eventName, ...)
local eventListeners = self.listeners[eventName]
if eventListeners then
for i = 1, #eventListeners do
eventListeners[i](...)
end
end
end

local dispatcher = EventDispatcher.new()

local callbackFunction = function(param1, param2)
print(param1, param2)
end

dispatcher:removeEventListener("eventName", callbackFunction)
dispatcher:addEventListener("eventName", callbackFunction)


dispatcher:dispatchEvent("eventName", "hello1", "world")
dispatcher:removeEventListener("eventName", callbackFunction)
dispatcher:dispatchEvent("eventName", "wang2", "world")