How to run a generic command before all existing mouse events in a script?

I have a LocalScript with TENS of MouseEnter, MouseLeave, MouseButton1Down events.
Inside each one, I run something different:

Text.MouseEnter:Connect(function()
	-- something
end)

Text.MouseLeave:Connect(function()
	-- something
end)

Button.MouseButton1Down:Connect(function()
	-- something
end)

I have a popup window, which, when displayed, NONE of the above events should fire.
Currently, I have to insert a line inside EACH event to prevent it from running:

Text.MouseEnter:Connect(function()
	if MyPopUp.Visible then return end
	-- something
end)

Text.MouseLeave:Connect(function()
	if MyPopUp.Visible then return end
	-- something
end)

Button.MouseButton1Down:Connect(function()
	if MyPopUp.Visible then return end
	-- something
end)

I ask: is there any way to have a function that intercepts ALL these events and disables them if this popup is visible WITHOUT NEEDING TO PUT AN IF INSIDE EACH EVENT?

Honestly, the repeated if statements is probably the way to go, even though it feels like a violation of the DRY principle. In such simple case, there isn’t really much of an advantage to transforming your code just to avoid a small bit of repetition.

However, if the multiple if statements is really bothering you, perhaps consider setting up a common function with a look-up table.

local events = {}

function events.MouseEnter(...)
	--something
end

function events.MouseLeave(...)
	--something
end

function events.MouseButton1Down(...)
	--something
end

function validate(event, ...)
	if MyPopUp.Visible then return end
	events[event](...)
end

Text.MouseEnter:Connect(function(...) validate("MouseEnter", ...) end)
Text.MouseLeave:Connect(function(...) validate("MouseLeave", ...) end)
Button.MouseButton1Down:Connect(function(...) validate("MouseButton1Down", ...) end)

Essentially, whenever one of the events is fired, the anonymous function calls the validate function with an identifier (the name of the event, in this case). The validate function ensures the context is safe to proceed, then it uses a look-up table to fire the function associated with the identifier.

This design pattern is advantageous in that it’s suitable for if you have more validation code. For example, if you wanted to validate more than if MyPopUp is not visible, you could simply add it to the validate function, as long as it applies to every one of the event contexts.

Again, it’s probably not worth overhauling your code just to implement such a minute, functional change, but this is how I would approach the problem if I needed to solve it.

1 Like

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