Events
Events are used for clients to receive realtime data from actors.
Publishing from actors
Actors can publish events to clients using this._broadcast and connection.send.
Broadcasting events
Actors can publish events to all connected clients with this._broadcast(name, data). For example:
chat_room.tsclient.ts
export default class ChatRoom extends Actor {
sendMessage(rpc: Rpc<ChatRoom>, message: string) {
this._broadcast('newMessage', { message });
}
}Sending events to specific connections
Actors can send messages to specific client connections. All connections are available on the this._connections array. For example:
chat_room.tsclient.ts
export default class ChatRoom extends Actor {
sendPrivateMessage(rpc: Rpc<ChatRoom>, connectionId: number, message: string) {
const conn = this._connections.find(c => c.id == connectionId);
conn.send('newMessage', { message });
}
}Subscribing from clients
Clients can subscribe to events from actors using on and once.
on(eventName, callback)
on(eventName, callback)Documentation
Clients can subscribe to events that will happen repeatedly using actor.on(name, callback). For example:
client.tschat_room.ts
const actor = client.get<ChatRoom>({ name: 'chat_room' });
actor.on('newMessage', ({ message }) => {
console.log('Message', message);
});once(eventName, callback)
once(eventName, callback)Documentation
Clients can listen for an event only one time with actor.once(name, callback). For example:
client.tschat_root.ts
const actor = client.get<ChatRoom>({ name: 'chat_room' });
actor.once('joinRequestApproved', () => {
// This will only be called once
console.log('Join request accepted');
});
await actor.requestJoin();Connections
Connections are used to communicate with clients from the actor.
Last updated