EntityStore: onOwner() method

Available since @irtio/client 5.0BrowsersNode

The onOwner() method of the EntityStore interface calls a function each time an entity of a kind in the client’s view gets a new owner, a player or the room.

Syntax

onOwner(kind, callback)
onOwner(kind, callback, options)

Parameters

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

A function called with one parameter:

entity
The ClientEntity whose owner changed, typed as its kind. Read the new owner with ownerOf().
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

The room changes an entity’s owner with Entities.setOwner(), and when a player’s presence ends, as the kind’s onOwnerLeave says. An entity that enters with an owner doesn’t call onOwner(); onEnter() runs for it, and ownerOf() gives its owner.

When the local player loses an entity, the client drops its unsent writes to it, and its writable fields can’t be set any more.

Examples

Showing who holds the flag

In a capture-the-flag game the room gives the flag to the player who picks it up, and back to the room when they drop it.

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

const Flag = entity("flag", { x: "f32", y: "f32", team: "u8" });
const schema = defineSchema({ entities: [Flag] });

const room = await connect("ctf-5", { schema });

room.entities.onOwner(Flag, (flag) => {
  const carrier = room.entities.ownerOf(flag);
  if (carrier === undefined) console.log(`team ${flag.team}'s flag is down`);
  else if (carrier === room.player) console.log("you have the flag, run");
  else console.log(`${carrier} has team ${flag.team}'s flag`);
});

See also

Runtime availability

BrowsersNode
onOwner()5.05.0