EventBus07 / 13

Events and EventBus

The sender announces a change, and subscribers decide how to respond.

EventBus connects services, components, and the FSM through events. When the score changes, the service sends ScoreChanged. The text node can respond on its own.

The service sends the event as shown below. BlockPuzzleGameplayService.ts

this.sceneContext.engine.events.emit({
  type: BlockPuzzleEvents.ScoreChanged,
  data: { score: this.getSession().score, delta },
});

The public emit method takes data. The subscriber receives an AppEvent with the same data in payload. Here is a shortened handler. BlockPuzzleScoreComponent.ts

const off = this.node.events.on(BlockPuzzleEvents.ScoreChanged, (event) => {
  const payload = SchemaDecoder.decode(
    event.payload,
    BlockPuzzleEventSchemas.ScoreChanged,
    BlockPuzzleEvents.ScoreChanged,
  );
  this.node.setText(String(payload.score));
});

The example combines subscribing and updating the text. The original component puts them in separate methods. Save the off function and call it when disabling the component.

01
Senderemit({ type, data })
02
EventBusMoves data to payload
03
SubscriberAppEvent → decoder → action
04
FSMEngineEventBridge queues the event in the active FSM
The bus changes the event wrapper. Validate the payload separately.

on subscribes to one event type, and onAny subscribes to all events. Both return a function that unsubscribes.

emit continues while asynchronous handlers finish. Use FSM commands when execution order matters.