summaryrefslogtreecommitdiff
path: root/EventMsgCenter/EventMsgCenter.lua
blob: 7b944c2bd826531cf2ed596a39b527bca442c539 (plain)
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
local EventMsgCenter = {} 

-- <event, {callbacks}>
local _broadcast = {}

EventMsgCenter.registerMsg = function(e, callback, first) 
	if _broadcast[e] == nil then 
		_broadcast[e] = {} 
	end
	first = first or false
	EventMsgCenter.unregisterMsg(e, callback)
	if not first then 
		table.insert(_broadcast[e], callback)
	else 
		table.insert(_broadcast[e], 1, callback)
	end 
end 

local removeElement = function(t, e)
	for i, v in ipairs(t) do 
		if v == e then 
			table.remove(t, i)
			break
		end 
	end 
end 

EventMsgCenter.unregisterMsg = function(e, callback)
	if _broadcast[e] == nil or callback == nil then 
		return 
	end 
	removeElement(_broadcast[e], callback)
end 

EventMsgCenter.unregisterAllMsgByEvent = function(e)
	_broadcast[e] = nil
end 

EventMsgCenter.unregisterAllMsg = function() 
	_broadcast = {}
end 

EventMsgCenter.sendMsg = function(e, ...)
	local callbacks = _broadcast[e]
	if callbacks == nil then 
		return 
	end 
	for _, f in ipairs(callbacks) do 
		if f ~= nil then 
			f(...)
		end 
	end 
end 

return EventMsgCenter