EntityStore: onEnter() method

Available since @irtio/client 5.0BrowsersNode

The onEnter() method of the EntityStore interface calls a function each time an entity of a kind enters the client’s view.

Syntax

onEnter(kind, callback)
onEnter(kind, callback, options)

Parameters

kind
A kind declared in the client’s schema.
callback

A function called with one parameter:

entity
The ClientEntity that entered, typed as its kind.
options Optional

An object with this property:

signal
An AbortSignal. When it aborts, the callback is removed, as addEventListener() removes a listener. If it has aborted already, the callback isn’t added.

Return value

A function that removes the callback.

Exceptions

Error
Thrown if the kind isn’t declared in the client’s schema.

Description

An entity enters when the room creates it in the client’s view, when it moves into the view, and when the room gives it to the local player, who sees what it owns wherever it is. Each entity in the full state enters too: in the first state update, and again after a change of generation or a reconnect the room can’t resume.

The callback runs once the whole state update is applied, so it sees the entity’s values and every other entity as of that update. It doesn’t run for the entities in view when it’s added; read those with all().

Examples

Adding a monster to the scene

Each monster that comes into view gets a sprite, and the abort signal removes the callback when the player leaves the level.

// monsters.ts
import { connect, defineSchema, entity } from "@irtio/client";

const Monster = entity("monster", { x: "f32", y: "f32", species: "u8" });
const schema = defineSchema({ entities: [Monster] });

const room = await connect("cave-1", { schema });
const level = new AbortController();

room.entities.onEnter(
  Monster,
  (monster) => console.log(`spawn sprite ${monster.species} at ${monster.x}, ${monster.y}`),
  { signal: level.signal },
);

// Leaving the level
level.abort();

See also

Runtime availability

BrowsersNode
onEnter()5.05.0