Events
Events are one of the basic tools for creating interactive and dynamic experiences. Events are how entities can communicate with each other through a flexible listener and dispatch system.
Event API
addListener
addListener registers a component to listen to an event.
Parameters
target: Eid
The eid of the entity that the listener is attached to.
name: string
The name of the event that the entity is listening for.
listener: Listener
The function that gets triggered when the event name is dispatched to the target entity or a entity that is a child of the entity the listener is attached to.
Listener Type:
type Event = {
target: Eid // The entity the event was dispatched on
currentTarget: Eid // The entity the event was listened on
name: string // The name of the event
data: unknown // The custom data emitted by the dispatcher
}
type Listener = (event: Event) => void
Example:
const handleCollision = (e) => { console.log("I touched another entity") }
// This listener logs a message whenever the entity collides with another entity.
world.events.addListener(component.eid, ecs.physics.COLLISION_START_EVENT, handleCollision)
removeListener
removeListener un-registers an existing listener. The eid, name, and exact reference to the listener callback is needed to remove the listener.
Parameters
target: Eid
The eid of the entity that the listener is attached to.
name: string
The name of the event that the entity is listening for.
listener: Listener
The function that gets triggered when the event name is dispatched to the target entity or a entity that is a child of the entity the listener is attached to.
Example:
const handleCollision = (e) => { console.log("I touched another entity") }
// This listener logs a message whenever the entity collides with another entity.
world.events.addListener(component.eid, ecs.physics.COLLISION_START_EVENT, handleCollision)
// This line removes the listener
world.events.removeListener(component.eid, ecs.physics.COLLISION_START_EVENT, handleCollision)
dispatch
dispatch is used to emit events that the listeners can listen to.
Parameters
target: Eid
The entity that is you want the dispatch to target.
name: string
The name of the event you want to dispatch.
data: unknown
Custom data that is optionally emitted by the dispatch call.
Example:
// This line emits an event to the eid of an enemy entity with the name attack with the
// damage the attack caused stored as the data parameter.
world.events.dispatch(eidOfEnemy, "attack", {damage: 10})