dezhou_client/lua_probject/base_project/Game/View/Common/EventManager.lua

109 lines
2.4 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

EventManager = {
Language = 1
}
-- 兼容 Lua 5.1 和 5.2+
local unpack = unpack or table.unpack
function EventManager:Init()
EventManager._events = {}
end
-- 注册事件监听器
function EventManager:EventAdd(eventName, callback)
if not self._events[eventName] then
self._events[eventName] = {}
end
-- 防止重复添加
for _, listener in ipairs(self._events[eventName]) do
if listener == callback then
return false
end
end
table.insert(self._events[eventName], callback)
return true
end
-- 取消注册
function EventManager:EventRemove(eventName, callback)
if not self._events[eventName] then
return false
end
for i, listener in ipairs(self._events[eventName]) do
if listener == callback then
table.remove(self._events[eventName], i)
return true
end
end
return false
end
-- 触发事件(使用兼容的 unpack
function EventManager:Call(eventName, ...)
if not self._events[eventName] then
return 0
end
local count = 0
-- 使用兼容的 unpack 函数
local listeners = { unpack(self._events[eventName]) }
for _, callback in ipairs(listeners) do
if type(callback) == "function" then
local success, result = pcall(callback, ...)
if not success then
print("事件回调错误:", result)
end
count = count + 1
end
end
return count
end
-- 替代方案:使用更安全的方式(推荐)
function EventManager:CallSafe(eventName, ...)
if not self._events[eventName] then
return 0
end
local count = 0
-- 安全复制数组
local listeners = {}
for i, v in ipairs(self._events[eventName]) do
listeners[i] = v
end
for _, callback in ipairs(listeners) do
if type(callback) == "function" then
local success, result = pcall(callback, ...)
if not success then
print("事件回调错误:", result)
end
count = count + 1
end
end
return count
end
-- 清空事件
function EventManager:clear(eventName)
if eventName then
self._events[eventName] = nil
else
self._events = {}
end
end
-- 获取监听器数量
function EventManager:getListenerCount(eventName)
if not self._events[eventName] then
return 0
end
return #self._events[eventName]
end