-
Notifications
You must be signed in to change notification settings - Fork 4
Events
samme edited this page Nov 4, 2024
·
7 revisions
Phaser 3 uses a slightly modified eventemitter3, as Phaser.Events.EventEmitter.
- Event names are strings
- The emitter chooses a default context (
this
value), but listeners can override this - The emitter chooses the callback arguments
-
on()
is the same asaddListener()
-
off()
is the same asremoveListener()
-
off()
with no arguments is the same asremoveAllListeners()
-
off()
can match event name; event name and listener; or event name, listener, and context; but no other combination - A listener added with
once()
is removed after its first call
All of Phaser's events (names, default context, arguments) are defined in the API.
Some Phaser classes (e.g., GameObject) extend Phaser.Events.EventEmitter directly, and some (e.g., Game, Scene) hold an emitter on their events
property.
You can emit and listen to your own events on these objects, but don't use any of Phaser's event names (e.g., "update"), and never remove listeners that aren't yours. Be careful of removing more than you meant to with off()
.
// NO (removes all listeners on all events)
this.game.events.off();
// NO (removes all listeners to `step`)
this.game.events.off('step');
// YES (same arguments used on `on()`)
this.game.events.off('step', this.onStep, this);
Remember that event emitters just hook up functions to other functions. The emitter doesn't know or care about any state associated with the listener. It's up to you to remove listeners when appropriate.