knucklebones/utils/event_bus.lua

44 lines
1.2 KiB
Lua
Raw Permalink Normal View History

2023-08-12 11:36:14 +02:00
--- @class EventBus
EventBus = {
_handlers = {},
new = function(self, o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end,
---
---@param self EventBus
---@param event any
---@param handler any
---@param index any
on = function(self, event, handler, index)
if not self._handlers[event] then self._handlers[event] = {} end
self:off(event, handler)
if not index then
table.insert(self._handlers[event], handler)
else
-- insertIntoTable(this.handlers[event], handler, index)
end
end,
---
---@param self EventBus
---@param event any
---@param handler any
off = function(self, event, handler)
if not self._handlers[event] then return end
self._handlers[event] = table.filter(self._handlers[event], function(o) return o ~= handler end)
end,
---
---@param self EventBus
---@param event any
---@param ... unknown
emit = function(self, event, ...)
trace("[EventBus] Emitted " .. event)
if not self._handlers[event] then return end
for k, handler in pairs(self._handlers[event]) do
handler(...)
end
end
}