-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEvents.lua
More file actions
59 lines (49 loc) · 1.64 KB
/
Events.lua
File metadata and controls
59 lines (49 loc) · 1.64 KB
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
-- Events.lua
-- Events facilitates message passing between objects.
-- Mostly for user generated events
-- but some internal events too like "won" or "died" or "moveDone"
-- Classes that respond to events should define a bindEvents method where all the events
-- are bound so that they can be easily rebinded if needed
Events = class()
Events.__callbacks = {}
function Events.bind(event,obj,func)
if not Events.__callbacks[event] then
Events.__callbacks[event] = {}
end
if not Events.__callbacks[event][obj] then
Events.__callbacks[event][obj] = {}
end
Events.__callbacks[event][obj][func] = 1
end
-- event is optional
function Events.unbind(obj,event)
for evt,cbs in pairs(Events.__callbacks) do
if event == nil or event == evt then
cbs[obj]=nil
end
end
end
function Events.unbindEvent(event)
Events.__callbacks[event] = nil
end
function Events.trigger(event,...)
if Events.__callbacks[event] then
-- make a clone of the callbacks. This is because callbacks
-- can bind or unbind events. for example Stage.play can
-- recreate its state and needs to rebind
local clone = {}
for obj,funcs in pairs(Events.__callbacks[event]) do
clone[obj] = {}
for func,dummy in pairs(funcs) do
clone[obj][func] = 1
end
end
for obj,funcs in pairs(clone) do
for func,dummy in pairs(funcs) do
local argCopy = Table.clone(arg)
table.insert(argCopy,1,obj)
func(unpack(argCopy))
end
end
end
end