2023-11-03 03:07:53 +02:00
|
|
|
extends Node
|
|
|
|
|
2024-03-16 19:45:43 +02:00
|
|
|
## A simple class to manage callbacks for different keys
|
2023-11-03 03:07:53 +02:00
|
|
|
class_name CallbackMap
|
|
|
|
|
2024-03-16 19:45:43 +02:00
|
|
|
## Map of callbacks
|
2023-11-03 03:07:53 +02:00
|
|
|
var callbacks := {}
|
2024-03-11 19:09:50 +02:00
|
|
|
var single_callbacks: Array = []
|
2023-11-03 03:07:53 +02:00
|
|
|
|
|
|
|
func add(key: Variant, callback: Callable) -> void:
|
|
|
|
_validate_key(key)
|
|
|
|
|
|
|
|
if callbacks.has(key):
|
|
|
|
callbacks[key].append(callback)
|
|
|
|
else:
|
|
|
|
callbacks[key] = [callback]
|
|
|
|
|
|
|
|
func add_once(key: Variant, callback: Callable) -> void:
|
|
|
|
_validate_key(key)
|
|
|
|
|
2024-03-11 19:09:50 +02:00
|
|
|
single_callbacks.append(callback)
|
2023-11-03 03:07:53 +02:00
|
|
|
|
2024-03-11 19:09:50 +02:00
|
|
|
add(key, callback)
|
2023-11-03 03:07:53 +02:00
|
|
|
|
|
|
|
func remove(key: Variant, callback: Callable) -> void:
|
|
|
|
_validate_key(key)
|
|
|
|
|
|
|
|
if callbacks.has(key):
|
|
|
|
callbacks[key].erase(callback)
|
|
|
|
|
2024-03-11 19:09:50 +02:00
|
|
|
if single_callbacks.has(callback):
|
|
|
|
single_callbacks.erase(callback)
|
|
|
|
|
2023-11-03 03:07:53 +02:00
|
|
|
func call_key(key: Variant, args: Array) -> void:
|
|
|
|
_validate_key(key)
|
|
|
|
|
|
|
|
if callbacks.has(key):
|
|
|
|
for callback in callbacks[key]:
|
|
|
|
callback.callv(args)
|
|
|
|
|
2024-03-11 19:09:50 +02:00
|
|
|
if single_callbacks.has(callback):
|
|
|
|
remove(key, callback)
|
|
|
|
|
2023-11-03 03:07:53 +02:00
|
|
|
func _validate_key(key: Variant):
|
2024-03-11 19:09:50 +02:00
|
|
|
assert(typeof(key) == TYPE_STRING||typeof(key) == TYPE_INT||typeof(key) == TYPE_FLOAT, "key must be a string or number")
|