简体   繁体   中英

Firing an event from Phaser game JS to outer JS?

I'm creating a Phaser game that will form part of a larger JS application. When a player completes a level I need the game to be hidden to move back to performing other tasks before the game shows again at a later stage on the next level.

I'm having a hard time finding a sensible way to fire an event (or another way to call a callback function) from a Phaser.Game to the JS that instantiated it.

The only think I've thought of at the moment is to manually add the callback to the game:

function onLevelComplete() {
  // example callback function
}

this.game = new Phaser.Game(800, 600, Phaser.AUTO, this.el);
this.game.levelCompleteCallback = onLevelComplete;

Then anywhere were the Phaser.Game is available (eg within a state) I could do this.game.levelCompleteCallback() .

The trouble is that this feels really tightly coupled. What I want is a way to do something like this.game.fireEvent('levelComplete') and not have to care whether there's anything listening at the other side.

Is there anything built in that I'm missing that would allow me to do what I need?

I would use a Signal from within your game:

this.onLevelComplete = new Phaser.Signal();

...

// some condition is met
this.onLevelComplete.dispatch();

As long as the Signal is exposed to the app above it can register itself with it quite easily. Perhaps a single global object (gameEvents?), or a route to the current State, or perhaps the game passes a reference to the events into the app somewhere. There are myriad ways of doing this.

function appDoesSomething() {}

gameEvents.onLevelComplete.add(this.appDoesSomething, this);

Either way, the end result is that the game can fire off the signals happily without caring if the app is listening or not.

It's impossible to have this set-up fully decoupled though, they are joined somewhere. It's just up to you where.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM