Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 36 ยท Game Architecture

Events, Registry and Saving

Decouple Phaser code with events, share state across scenes with the registry and data manager, and save progress safely with localStorage.

As soon as a game has more than a few objects, the question "who tells whom?" decides whether the code stays clean. If the enemy class directly changes the score text, the score text must be reachable from the enemy; the HUD becomes a dependency of every object that scores. The solution is to let objects announce that something happened, and let anyone interested listen. Phaser is built on this idea: its own systems (input, tweens, cameras, scenes) all communicate with events.

This lesson covers four related tools: event emitters, the global registry, the data manager attached to game objects, and saving state to the browser so that progress survives a reload.

Event emitters

An event emitter has three core methods:

  • emitter.on('name', callback, context) registers a listener.
  • emitter.emit('name', ...args) runs every listener with those arguments.
  • emitter.off('name', callback, context) removes a listener. once registers a listener that removes itself after the first call.

Phaser objects that are emitters include a scene (this.events), the whole game (this.game.events), the registry (this.registry.events), input, cameras, tweens and every game object. You can also create your own bus:

JavaScript
const bus = new Phaser.Events.EventEmitter();
bus.on('coin-collected', (value) => console.log('+', value));
bus.emit('coin-collected', 5);

Which emitter should you pick? A rule of thumb:

Who needs to hear it Use
Things inside one scene this.events of that scene
Another scene (HUD, audio) The sender scene's events, or this.game.events
Anything, anywhere A shared bus object (this.game.events or your own emitter)
Changes of one value A registry or data manager changedata event

Name events consistently ('player-hit', 'level-complete') and keep a list of them in one file as constants. A mistyped event name never throws, it simply never arrives.

An event bus in action

Below, a coin pickup does not know about the score display, the sound or the achievement. It emits one event. Three independent listeners react, and you can add or remove a listener without touching the pickup code.

Decoupling with events

The most important line is the cleanup: removeAllListeners() on a game-wide emitter is only safe if this scene is the only user. In a bigger game remove the individual callbacks with off(name, fn) so that other scenes' listeners stay.

The registry: shared state

An emitter is for messages. For values that several scenes need (current level, lives, settings), Phaser provides the registry, a game-wide key/value store (this.registry, available in every scene). It is a DataManager, so it fires events when a value changes:

JavaScript
this.registry.set('lives', 3);
const lives = this.registry.get('lives');
this.registry.inc('lives', -1);           // numeric helper: add (or subtract) a number
this.registry.events.on('changedata-lives', (parent, value, previous) => { /* update hearts */ });

changedata-<key> fires for one key and changedata fires for any key, with the arguments (parent, key, value, previous). Subscribing in the HUD scene means the HUD redraws itself whenever any part of the game changes the value, and no scene needs a reference to another.

Data on game objects

Every game object has a data manager too. enemy.setData('hp', 30) stores a value on it, enemy.getData('hp') reads it, and enemy.on('changedata-hp', ...) reacts to changes. This is convenient for small amounts of data and for tools that attach custom properties from a Tiled map. For heavy gameplay you will usually prefer real class fields (this.hp), because they are faster and your editor can autocomplete them.

Registry shared by two scenes

The Game scene never mentions the HUD's text objects, and the Hud never calls the game. They only share keys. Every button press logs the changed key to the console, and the HUD redraws from that one listener.

Saving progress

State in the registry vanishes when the page reloads. To keep it, save to the browser. The most common storage for a web game is localStorage: a small key/value store for strings (typically 5 MB), kept per site. Save JSON and read it back:

JavaScript
// writing
localStorage.setItem('mygame.save', JSON.stringify({ version: 1, level: 4, coins: 120 }));
// reading
const raw = localStorage.getItem('mygame.save');
const save = raw ? JSON.parse(raw) : null;

Three habits make saving robust:

  1. Wrap storage in try/catch. localStorage can throw: private browsing, blocked cookies, a full quota, embedded pages in sandboxed frames (like the examples on this page). A game that crashes at start because it cannot save is worse than a game that cannot save.
  2. Version your save format. Put a version number in the data, and write a small migrate() function so that old saves keep working after you add new fields.
  3. Validate what you read. Players (and browser extensions) can edit local storage. Fall back to defaults when a value is missing or the JSON does not parse.

For larger data, such as a level editor's maps, use IndexedDB (via a library like idb), and for cloud saves send the same JSON to your server. The format stays the same.

A save manager with a safe fallback

Here the storage code lives in one class. It tries localStorage and, when the browser refuses (as it does inside this lesson's sandbox), falls back to an in-memory object. The game code never needs to know which one is in use.

SaveManager with fallback

Click, press Save, click more and press Load: the score goes back to the saved value, and the status line says where the data went. Inside this sandboxed lesson the backend is memory, so a page reload forgets it. On your own site the very same class writes to localStorage and the score survives a reload. The migration step shows why a version field matters: a version 1 save without a best field is upgraded when loaded.

When to save

  • After meaningful events: a level completed, a purchase, a settings change. Not every frame.
  • On visibilitychange (tab hidden) and beforeunload, as a safety net.
  • Never store secrets or anything the player must not edit (paid unlocks are verified on the server).
  • Keep saves small: store IDs and numbers, not whole game objects. JSON.stringify cannot serialize Phaser objects, which contain circular references.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which tool is best for announcing 'the player was hit' to unrelated systems such as sound and HUD?

    An emitter lets the sender announce an event without knowing who listens, so systems stay decoupled.
  2. 2. What does registry.events.on('changedata-lives', fn) do?

    Data managers emit changedata-key events whenever a key's value is set to something new.
  3. 3. Why should reads and writes of localStorage be wrapped in try/catch?

    Browsers can block or limit storage. A failed save should not crash the game.
  4. 4. What is the purpose of a version field in save data?

    When you add or rename fields later, the version tells your loader how to upgrade older saves.
  5. 5. What happens if a scene registers a listener on this.game.events but never removes it before restarting?

    The game emitter outlives the scene, so stale listeners pile up. Remove them in the scene's shutdown handler.

Summary

  • Emitters (this.events, this.game.events, your own) decouple senders from listeners; remove listeners you add to long-lived emitters.
  • The registry stores values shared across scenes and fires changedata events, so a HUD can follow state without a direct link.
  • Game objects have their own data managers (setData, getData).
  • Save with localStorage and JSON inside try/catch, include a version, validate on load, and keep a fallback.
  • Save on meaningful events, keep the saved data small and plain.

Next: Scale Manager and Mobile