[SOLVED] How to run a function once in Object-Oriented Programming?
Asked by
2 years ago Edited 2 years ago
Hello. I'm trying to make my own Custom Signal module without using BindableEvents nor using a module from the DevForum. But I don't know how to make the handler Signal:Once()
which basically uses Connect but only does it once. I tried using coroutines, debounce, and setting the function to nil, but it still runs more than once like Signal:Connect()
and not like RBXScriptSignal:Once()
. Here's the module for reference:
02 | module.__index = module |
04 | local backupBindableEvent = Instance.new( "BindableEvent" ) |
06 | function module.new(signalName: string) |
07 | local self = setmetatable ( { } , module) |
10 | local newSignalName: string |
12 | if signalName ~ = nil then |
13 | newSignalName = signalName |
15 | newSignalName = "Event" |
18 | self._listeners = require(script.Listeners).new() |
19 | local listenersModule = self._listeners |
21 | function newSignal:Connect(func) |
22 | listenersModule:AddListener(func) |
26 | Disconnect = function (self) |
27 | listenersModule:RemoveListener(func) |
28 | self.Connected = false |
33 | function newSignal:ConnectParallel(func) |
35 | listenersModule:AddListener(func) |
38 | Disconnect = function (self) |
39 | listenersModule:RemoveListener(func) |
40 | self.Connected = false |
45 | function newSignal:Once(func) |
46 | return backupBindableEvent.Event:Once(func) |
49 | function newSignal:Wait() |
50 | return backupBindableEvent.Event:Wait() |
53 | self [ newSignalName ] = newSignal |
58 | function module:Fire(...: any) |
59 | local paramsTable = table.pack(...) |
61 | backupBindableEvent:Fire(table. unpack (paramsTable)) |
64 | local listenersModule = self._listeners |
66 | repeat task.wait() until listenersModule:GetListenersAsync() ~ = nil |
67 | local listenersTable = listenersModule:GetListenersAsync() |
69 | if listenersTable ~ = nil then |
70 | for _, listenerFunc in pairs (listenersTable) do |
72 | listenerFunc(table. unpack (paramsTable)) |
Also I don't know how to make the Signal:Wait()
function. Right now, I'm temporarily using BindableEvents to make those functions work.
And also, if you noticed anything wrong in my module that is off-topic, lemme know!