Hocuspocus Provider Events

Introduction

Events are a great way to react to different states, for example when the provider has successfully connected. You can choose to bind event listeners on initialization or later, that’s up to you.

Option 1: Configuration

Passing event listeners to the constructor ensures they are registered during initialization.

const provider = new HocuspocusProvider({
  url: "ws://127.0.0.1:1234",
  name: "example-document",
  document: ydoc,
  onOpen() {
    // …
  },
  onConnect() {
    // …
  },
  onAuthenticated() {
    // …
  },
  onAuthenticationFailed: ({ reason }) => {
    // …
  },
  onStatus: ({ status }) => {
    // …
  },
  onMessage: ({ event, message }) => {
    // …
  },
  onOutgoingMessage: ({ message }) => {
    // …
  },
  onSynced: ({ state }) => {
    // …
  },
  onClose: ({ event }) => {
    // …
  },
  onDisconnect: ({ event }) => {
    // …
  },
  onDestroy() {
    // …
  },
  onAwarenessUpdate: ({ added, updated, removed }) => {
    // …
  },
  onAwarenessChange: ({ states }) => {
    // …
  },
  onStateless: ({ payload }) => {
    // ...
    // the provider can also send a custom message to the server: provider.sendStateless('any string payload')
  }
});

Option 2: Binding

Sometimes you want to register an event listener after the initialization, even if it’s right after. Also, that’s a great way to bind and unbind event listeners.

Bind event listeners

const provider = new HocuspocusProvider({
  // …
});

provider.on("synced", () => {
  // …
});

Unbind event listeners

const onMessage = () => {
  // A new message comes in
};

// Bind …
provider.on("onMessage", onMessage);

// … and unbind.
provider.off("onMessage", onMessage);

List of events

NameDescription
openWhen the WebSocket connection is created.
connectWhen the provider has successfully connected to the server.
authenticatedWhen the client has successfully authenticated.
authenticationFailedWhen the client authentication was not successful.
statusWhen the connections status changes.
messageWhen a message is incoming.
outgoingMessageWhen a message will be sent.
syncedWhen the Y.js document is successfully synced (initially).
closeWhen the WebSocket connection is closed.
disconnectWhen the provider disconnects.
destroyWhen the provider will be destroyed.
awarenessUpdateWhen the awareness updates (see https://docs.yjs.dev/api/about-awareness)
awarenessChangeWhen the awareness changes (see https://docs.yjs.dev/api/about-awareness)
statelessWhen the stateless message was received.