brackeys-12/components/Triggerer/triggerer.gd

41 lines
1.3 KiB
GDScript3
Raw Normal View History

2024-09-08 17:34:41 +00:00
@icon("res://components/Triggerer/radio.svg")
extends Base
## A trigger object to trigger things and read in triggers
##
## An object used for other objects to connect to for triggers.
## Objects can call the read function with a callback function to
## read in future triggers of a key to that callback. Objects can
## then call the trigger function to trigger everything listening
## to a key.
var _connections = {}
## Trigger an event to be read in by other objects
func trigger(key: String, data: Dictionary = {}) -> void:
2024-09-15 09:22:08 +00:00
#_info("Triggered key ∧%s∧" % [key])
2024-09-08 17:34:41 +00:00
data.trigger = key
if _connections.has(key):
_connections[key] = _connections[key].filter(func(x): return x.is_valid())
for callback in _connections[key]:
callback.call(data)
if _connections.has("any"):
_connections["any"] = _connections["any"].filter(func(x): return x.is_valid())
for callback in _connections["any"]:
callback.call(data)
## Read in future triggers of a key to a callback
func listen(key: String, callback: Callable) -> void:
if not _connections.has(key):
_info("Created new connection key ∧%s" % [key])
_connections[key] = []
_info("Callback %s on →%s← added to key ∧%s" % [callback.get_method(), callback.get_object().name, key])
_connections[key].push_back(callback)