boris0dev Posted December 11, 2017 Share Posted December 11, 2017 Hi, I'm looking for an explanation for the following behaviour: I have a class "Main" extending Phaser.State, a class "Emitter" and a class "Receiver" extending Phaser.Sprite If I dispatch a signal from "Emitter" and listen to it in "Receiver" everything works as expected or to be more precise: "this.game" has the object "App" assigned. If I reload the state and dispatch again the signal two things happen: The listener receives the signal two times. The 1st time "this.game" is null, the 2nd time "this.game" contains again the object "App" (please have a look at the screenshot showing the console output) Does anybody have an explanation for this behaviour? Thanks, Boris The code (TypeScript) export class Game extends Phaser.Game { constructor() { super(480, 640, Phaser.AUTO, 'content', null); this.state.add('Main', Main, true); console.log("Game started"); } } class Main extends Phaser.State { private emitter: Emitter; private receiver: Receiver; preload() { this.load.image('logo', 'assets/logo.png'); } create() { this.emitter = new Emitter(this.game); this.receiver = new Receiver(this.game); const rKey = this.input.keyboard.addKey(Phaser.Keyboard.R); rKey.onDown.add(() => { console.log('reload state Main'); this.game.state.start('Main',true,false); }, this); } } class Emitter { // -- Signals static onEventFromEmitter: Phaser.Signal = new Phaser.Signal(); constructor(private game: Phaser.Game) { const spaceKey = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); spaceKey.onDown.add(() => { Emitter.onEventFromEmitter.dispatch(); }, this); } } class Receiver extends Phaser.Sprite { constructor(game: Phaser.Game) { super(game, 0, 0, 'logo'); this.game.add.existing(this); this.subscribe(); } /** * Subscribe to events */ private subscribe(): void { Emitter.onEventFromEmitter.add(() => { console.log('Game object in Receiver, listening to onEventFromEmitter', this.game); }, this); } } Link to comment Share on other sites More sharing options...
boris0dev Posted December 17, 2017 Author Share Posted December 17, 2017 I guess I've solved the issue: The state "Main" must remove in its shutdown method all event listeners from Emitter.onEventFromEmitter: class Main extends Phaser.State { shutdown() { Emitter.onEventFromEmitter.removeAll(); } } quiphop 1 Link to comment Share on other sites More sharing options...
Recommended Posts