I’ve recently created a Binder module similar to the one they showed in the ROBLOX video about 5 powerful code design patterns because I can’t find anything like it online and I also wanted to create for personal use.
Any improvements that I could apply on my module?
local Binder = {}
Binder.__index = Binder
-- Services
local CollectionService = game:GetService("CollectionService")
-- Variables
local Trove = require(script.Trove)
-- Main
function Binder.new(tag: string, class)
local self = setmetatable({
_trove = Trove.new(),
_tag = tag,
_bounded = false,
_classes = {},
_class = class,
}, Binder)
self.BindAdded = CollectionService:GetInstanceAddedSignal(self._tag)
self.BindRemoved = CollectionService:GetInstanceRemovedSignal(self._tag)
function self:Bind()
if not self._bounded then self._bounded = true end
self._trove:Add(
self.BindAdded:Connect(function(instance)
self._classes[instance] = self._class.new(instance)
print("Binded to " .. instance.Name)
end)
)
self._trove:Add(
self.BindRemoved:Connect(function(instance)
self._classes[instance]:Destroy()
self._classes[instance] = nil
print("Unbinded " .. instance.Name)
end)
)
for _, instance in pairs(CollectionService:GetTagged(self._tag)) do
self._classes[instance] = self._class.new(instance)
end
end
function self:Unbind()
if self._bounded then
print("Bind unbinded")
self._trove:Clean()
for instance, classObject in pairs(self._classes) do
classObject:Destroy()
self._classes[instance] = nil
print("Bind destroyed and cleaned up")
end
else
error("You can't unbind if you haven't bind anything yet")
end
end
print("New bind created")
return self
end
return Binder