meshcore.js
Events

Handlers and isolation

EventBuilder, typed handlers, registration order and error isolation.

An EventBuilder picks one of the client's events with setEvent(). The name is checked against ClientEvents, so the handler's extra arguments are typed to match. A contactAdd handler receives a Contact, a messageCreate handler a Message.

events/ready.ts
export default new EventBuilder()
  .setEvent('ready')
  .setOnce()
  .setHandler((client) => {
    console.log(`${client.self.name} is ready`);
  });

setOnce() runs the handler once and removes it. Without it the handler keeps running.

An event is a file under events/ with the builder as default export, loaded at login like any brick.

Order and isolation

Handlers of the same event run in registration order. One that throws or rejects is reported through the error event with source.type set to event and source.name set to the event's name. The others still run.

events/welcome.ts, events/log.ts
export const welcome = new EventBuilder().setEvent('contactAdd').setHandler((_client, contact) => {
  throw new Error(`could not welcome ${contact.name}`);
});

export const log = new EventBuilder().setEvent('contactAdd').setHandler((_client, contact) => {
  console.log(`still runs for ${contact.name}`);
});
main.ts
client.on('error', (error, source) => {
  if (source.type === 'event') console.error(`event "${source.name}" failed:`, error);
});

Reference

On this page