概述
最近在学习Xlua与项目的结合,在这里我们要时间的内容有
监听事件消息,触发事件消息,移除事件消息,在监听与触发的时候都需要能够传值给监听方法
实现
写个基本的创建类的方法,用于给事件消息创建对象
function simpleclass()
local class_type = {}
class_type.new = function()
local self = {}
setmetatable( self , {__index = class_type})
return self
end
return class_type
end
创建事件消息对象
require("simpleclass")
local EventMessage = simpleclass()
function EventMessage:Create()
local obj = EventMessage:new()
obj.data = {}
return obj
end
添加监听
--[[
self.data 装的是事件信息表
结构分析
data [事件名]= {
callback 回调函数
enable 是否激活回调
attachParam 回调参数
}
]]
function EventMessage:AddNotify(event_name, callback, attachParam)
if (event_name == nil
or callback == nil
or type(callback) ~= "function"
or type(event_name) ~= "string") then
__LogError("AddNotify error.param invaild")
return
end
if (self.data[event_name] == nil) then
self.data[event_name] = {}
end
for i,v in ipairs(self.data[event_name]) do
if (v.callback == callback) then
if (v.enable == false) then
v.enable = true
v.attachParam = attachParam
else
__LogError("AddNotify error.repeat added. "..event_name)
end
return
end
end
table.insert(self.data[event_name], {callback = callback, attachParam = attachParam, enable = true})
end
移除监听并不会做删除操作,只是禁用
function EventMessage:RemoveNotify(event_name, callback)
if (event_name == nil
or callback == nil
or type(callback) ~= "function"
or type(event_name) ~= "string") then
__LogError("RemoveNotify error.param invalid.")
return
end
if (self.data[event_name] == nil) then
return
end
for i,v in ipairs(self.data[event_name]) do
if (v.callback == callback) then
v.enable = false
return
end
end
end
消息触发
function EventMessage:Notify(event_name, value)
if event_name ==nil or (self.data[event_name] == nil) then
return
end
local flag = true
for i,v in ipairs(self.data[event_name]) do
if (v.enable == true) then
v.callback(value, v.attachParam)
else
flag = false
end
end
if (flag == false) then
for i,v in ipairs(self.data[event_name]) do
if (v.enable == false) then
table.remove(self.data[event_name], i)
end
end
end
end
使用
监听:
local function Refsh(val,self)
print("现在的状态是"..val)
end
function AddNotify()
__EventMessage:AddNotify("StartGame", Refsh,self)
end
移除
function RemoveNotify()
__EventMessage:RemoveNotify("StartGame", Refsh)
end
触发
local function Start()
__EventMessage:Notify("StartGame", "开始游戏")
end