EntityStore: onLeave() method
@irtio/client 5.0BrowsersNodeThe onLeave() method of the EntityStore interface calls a function each time an entity of a kind leaves the client’s view.
Syntax
onLeave(kind, callback)
onLeave(kind, callback, options)
Parameters
kind- A kind declared in the client’s schema.
callback-
A function called with one parameter:
entity- The
ClientEntitythat left, typed as its kind, with the values it last had.
optionsOptional-
An object with this property:
signal- An
AbortSignal. When it aborts, the callback is removed, asaddEventListener()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 leaves when the room deletes it and when it moves out of the client’s view, and the client can’t tell the two apart: an entity that leaves the view can enter again later, with the same ID. On a change of generation, or a reconnect the room can’t resume, every entity leaves before the full state enters again.
By the time the callback runs, the store no longer holds the entity: get() returns undefined for its ID. Writing a field of an entity that left throws an Error.
Examples
Removing a bullet’s sprite
The client keeps a sprite for each bullet in view and drops it when the bullet leaves, whether it hit something or flew out of view.
// bullets.ts
import { connect, defineSchema, entity } from "@irtio/client";
const Bullet = entity("bullet", { x: "f32", y: "f32" });
const schema = defineSchema({ entities: [Bullet] });
const room = await connect("arena-3", { schema });
const sprites = new Map<number, string>();
room.entities.onEnter(Bullet, (bullet) => sprites.set(bullet.id, `bullet-${bullet.id}`));
room.entities.onLeave(Bullet, (bullet) => {
console.log(`remove ${sprites.get(bullet.id)}`);
sprites.delete(bullet.id);
});
See also
EntityStore.onEnter()Entities.delete(), the room’s side- Interest
Runtime availability
| Browsers | Node | |
|---|---|---|
onLeave() | 5.0 | 5.0 |