I have been trying to learn about Luau and made this simple event class.
Is there any benefit to handling events this way as opposed to BindableEvents? I think I read about issues with firing BindableEvents from within an object, so maybe this could be good for that.
--!strict
local Event = {}
Event.__index = Event
type func = () -> any
function Event.new()
local self = setmetatable({}, Event)
self.Subscribers = {}
return self
end
function Event:subscribe(callback : func)
table.insert(self.Subscribers, callback)
end
function Event:unsubscribe(callback : func)
local subscriber = table.find(self.Subscribers, callback)
if subscriber then
table.remove(self.Subscribers, subscriber)
end
end
function Event:fire(...)
for i, func in self.Subscribers do
--Was previously: func(...)
task.spawn(func, ...)
end
end
return Event
Also I’m not sure if this is the correct way to type check if something is a function.
type func = () -> any
Let me know your thoughts and any ways this could be done better.