Created
April 27, 2019 13:54
-
-
Save erodozer/74f404f1df019f5b429a8c13fc8f327f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node | |
""" | |
@author nhydock | |
Global Event Bus allows for registration and fan-out signal like | |
message passing between arbitrary objects. Add this as a singleton | |
to your project for easy usage. | |
In actuality is a super generic signal register. | |
Nodes can be notified of events from the bus by being part of the | |
'consumer' group and having the _on_event method handler | |
""" | |
var consumers = {} | |
func _enter_tree(): | |
get_tree().connect("node_added", self, "_add_listener") | |
get_tree().connect("node_removed", self, "_remove_listener") | |
func _add_listener(node: Node): | |
if node.is_in_group("consumer"): | |
for type in node._events(): | |
var listeners: Array = consumers.get(type, []) | |
listeners.append(node) | |
consumers[type] = listeners | |
func _remove_listener(node: Node): | |
if node.is_in_group("consumer"): | |
for type in node._events(): | |
var listeners: Array = consumers.get(type, []) | |
listeners.remove(listeners.find(node)) | |
func publish(type, payload={}): | |
for consumer in consumers.get(type, []): | |
consumer.call_deferred("_on_event", type, payload) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment