--******************************************************************
-- 文件名: MessageSlot.lu
-- 版 权: (C) 从这里开始
-- 创建人: 陈泽丹
-- 日 期: 2014-10-26 14:12
-- 版 本: 1.0
-- 描 述:
--************************** 修改记录 ******************************
-- 修改人:
-- 日 期:
-- 描 述:
--******************************************************************
-- 消息链
function MsgList()
local public = {}
local private = {}
private.listeners = {}
----------------------------
-- 订阅
function public:subscibe( _msgID, _fun )
if nil == private.listeners then
private.listeners = {}
end
table.insert( private.listeners, _fun )
end
-- 取消
function public:unSubscibe( _msgID, _fun )
if nil == private.listeners then
return
end
for i, v in pairs( private.listeners ) do
if v == _fun then
table.remove( private.listeners, i )
if 1 == #private.listeners then
private.listeners = nil
end
return
end
end
end
-- 发现
function public:find( _msgID, ... )
if nil == private.listeners then
return nil
end
local len = #private.listeners
for i=1, len do
if private.listeners*( ... ) then
return private.listeners*
end
end
return nil
end
-- 遍历
function public:forEach( _msgID, ... )
if nil == private.listeners then
return nil
end
local len = #private.listeners
for i=1, len do
private.listeners*( ... )
end
end
-- 清空
function public:release()
private.listeners = {}
end
return public
end
-- 消息机
function MessageSlot()
local public = {}
public.vote = MsgList()
public.action = MsgList()
public.done = MsgList()
local voteMsg = public.vote.find
local actionMsg = public.action.forEach
local doneMsg = public.done.forEach
public.vote.find = nil
public.vote.forEach = nil
public.action.find = nil
public.action.forEach = nil
public.done.find = nil
public.done.forEach = nil
----------------------------
-- 否决
function public:voteMessage( _msgID, ... )
if nil ~= voteMsg( public.vote, _msgID, ... ) then
return true
end
return false
end
-- 开火
function public:fireMessage( _msgID, ... )
actionMsg( public.action, _msgID, ... )
doneMsg( public.done, _msgID, ... )
end
-- 触发
function public:onMessage( _msgID, ... )
if not public:voteMessage( _msgID, ... ) then
public:fireMessage( _msgID, ... )
end
end
----------------------------
return public
end
***
msgSlot = MessageSlot()
function Vote()
cclog("Vote")
return true
end
function action()
cclog("action")
end
function done()
cclog("done")
end
msgSlot.vote:subscibe( 1, Vote )
msgSlot.action:subscibe( 1, action )
msgSlot.done:subscibe( 1, done )
msgSlot:onMessage( 1 )
msgSlot.vote:unSubscibe( 1, Vote )
msgSlot.action:unSubscibe( 1, action )
msgSlot.done:unSubscibe( 1, done )