-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSignal.lua
66 lines (52 loc) · 1.19 KB
/
Signal.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
local oo = require "oo"
local Listener = oo.class()
function Listener:init(f, scope)
self.func = f
self.scope = scope
end
function Listener:__call(...)
if self.scope == nil then
self.func(...)
else
self.func(self.scope, ...)
end
end
local Signal = oo.class()
function Signal:init()
self.listeners = {}
end
local function getListenerPos(self, func, scope)
for pos, l in ipairs(self.listeners) do
if l.func == func and l.scope == scope then
return pos
end
end
end
function Signal:add(func, scope)
local l = Listener.new(func, scope)
table.insert(self.listeners, l)
return l
end
function Signal:addOnce(func, scope)
self:add(func, scope).once = true
end
function Signal:remove(func, scope)
table.remove(self.listeners, getListenerPos(self, func, scope))
end
function Signal:removeAll()
for i in ipairs(self.listeners) do
self.listeners[i] = nil
end
end
function Signal:dispatch(...)
for i, l in ipairs(self.listeners) do
l(...)
if l.once then
table.remove(self.listeners, i)
end
end
end
function Signal:__call(...)
self:dispatch(...)
end
return Signal