A Scene Plugin that emits events and clears listeners when the Scene shuts down.
Plugin
const EventEmitter = Phaser.Events.EventEmitter;
const ScenePlugin = Phaser.Plugins.ScenePlugin;
/**
* @classdesc
* EphemeralEventEmitter is a Scene Plugin that emits events.
* Its listeners are automatically cleared when its Scene shuts down.
*
* @class EphemeralEventEmitter
* @extends Phaser.Events.EventEmitter
*
* @param {Phaser.Scene} scene - The Scene that has installed this plugin.
* @param {Phaser.Plugins.PluginManager} pluginManager - The Plugin Manager.
* @param {string} pluginKey - The key under which this plugin has been installed into the Scene Systems.
*/
class EphemeralEventEmitter extends EventEmitter {
constructor(scene, pluginManager, pluginKey) {
super();
ScenePlugin.call(this, scene, pluginManager, pluginKey);
}
/**
* Called when the Scene boots.
*/
boot() {
this.systems.events.on('shutdown', this.shutdown, this);
this.systems.events.on('destroy', this.destroy, this);
}
/**
* Destroys this plugin, removing all listeners and releasing all references.
*/
destroy() {
this.shutdown();
this.systems.events.off('shutdown', this.shutdown, this);
ScenePlugin.prototype.destroy.call(this);
}
}
Game configuration
new Phaser.Game({
plugins: {
// You can use any `mapping`.
scene: [{ key: 'EphemeralEventEmitter', plugin: EphemeralEventEmitter, mapping: 'ee' }]
}
});
Use in a scene
// These event handlers won't stack up after a restart.
this.ee.on('create', this.addNeuromancer, this);
this.ee.on('create', this.incCount, this);
this.ee.emit('create');