Feedback on custom event module?

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.

The functions are not run in task.spawn or coroutines, so each function will have to wait for the one in front of it to yield.

Some other people have beat you to the punch in terms of creating custom events, but this is still really nice code except for the issue mentioned above.

Oh you are correct, thank you. I’ll update it now.

In the process of doing that I noticed this:

Would this be better than what I’m currently doing?

type func = (...any) -> (...any)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.