# Events

### Publishing from actors <a href="#publishing-from-actors" id="publishing-from-actors"></a>

Actors can publish events to clients using `this._broadcast` and `connection.send`.

#### Broadcasting events <a href="#broadcasting-events" id="broadcasting-events"></a>

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 <a href="#sending-events-to-specific-connections" id="sending-events-to-specific-connections"></a>

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 <a href="#subscribing-from-clients" id="subscribing-from-clients"></a>

Clients can subscribe to events from actors using `on` and `once`.

#### `on(eventName, callback)` <a href="#on-event-name-callback" id="on-event-name-callback"></a>

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)` <a href="#once-event-name-callback" id="once-event-name-callback"></a>

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 <a href="#connections" id="connections"></a>

Connections are used to communicate with clients from the actor.
