-
Notifications
You must be signed in to change notification settings - Fork 5
A3. Events
This section explains how to publish, subscribe and process application events using the built-in EventDispatcher
.
To use the implementations refered on this section you must include the following module(s):
- pixel-commons (dependency of pixel-core)
You can use the EventDispatcher
to trigger events across decoupled components. An event can be published to a given [event name] and processed by multiple subscribers (as many as subscribed to the given event). This can be very useful to quickly propagate state changes throughout your game.
The EventDispatcher
is available as an instanceable class:
EventDispatcher dispatcher = new EventDispatcher();
Alternatively, you can use the static default event dispatcher, as follows:
EventDispatcher dispatcher = EventDispatcher.getDefault();
To subscribe to an event (example of a "collision" event):
dispatcher.subscribe("collision", CollisionData.class, (data) -> {
// ...
});
In the example above, the event name is "collision". Note that there is a class reference as the second argument, this binds "collision" events that are being published with a CollisionData
value. In this scenario, the data
value is automatically casted to the 2nd argument class type.
You can set the same event with different class references. The
EventDispatcher
filters by both (event name and class type).
Another example:
dispatcher.subscribe("collision", (data) -> {
// ...
});
This is similar to the prior example but without the class reference filter. This subscription will catch any "collision" event regardless of the value type.
To publish an event (again, "collision" is an example event name):
dispatcher.publish("collision", value);
To unsubscribe:
dispatcher.unsubscribe("collision", collisionListener);