aboutsummaryrefslogtreecommitdiff
path: root/bin/EventMsgCenter/EventMsgCenter.lua
diff options
context:
space:
mode:
authorchai <chaifix@163.com>2018-08-08 21:42:33 +0800
committerchai <chaifix@163.com>2018-08-08 21:42:33 +0800
commita03a35b6cfe6399ceaff86a1cc035f1131427955 (patch)
treeef20b98e6d74ca8a7c2d612b0ef8ad56f1f74a3b /bin/EventMsgCenter/EventMsgCenter.lua
parentc302ed889e01dcca8fd15ccca34e9f23972c8704 (diff)
*update
Diffstat (limited to 'bin/EventMsgCenter/EventMsgCenter.lua')
-rw-r--r--bin/EventMsgCenter/EventMsgCenter.lua55
1 files changed, 55 insertions, 0 deletions
diff --git a/bin/EventMsgCenter/EventMsgCenter.lua b/bin/EventMsgCenter/EventMsgCenter.lua
new file mode 100644
index 0000000..7b944c2
--- /dev/null
+++ b/bin/EventMsgCenter/EventMsgCenter.lua
@@ -0,0 +1,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 \ No newline at end of file