Docs
Events

Events

Simple pub/sub implementation for events.

Zermatt comes with a powerful pub/sub implementation that allows all Javascript code to emit and react to one or several events. Synchronously or asynchronously.

Dispatch an event

Event without data:

Zermatt.Event.dispatch('some:event')

Event with data:

Zermatt.Event.dispatch('some:event', {key: value})

Subscribe to events

Here are the definition and use of the on, once, waitOn, or waitOnce methods.

Zermatt.Event.[on | once | waitOn | waitOnce](events: string | string[], callback?: (CustomEvents[]) => void): {}

You can call Zermat.Event.on(), Zermat.Event.once(), Zermat.Event.waitOn(), Zermat.Event.waitOnce(). And, as arguments:

  • a single event to subscribe to, as a string or several events to subscribe to, as an array of strings,
  • an optional callback which receives an array of the dispatched events of type CustomEvent.

The function returns a subscriber object which you can use to unsubscribe to one or several events. See below "Unsubscribe from events".

Zermat.Event.on

The callback is called each time the events are dispatched.

Zermat.Event.once

The callback is called only once per event.

Zermat.Event.waitOn

The callback is called each time, only when all events are dispatched.

Zermat.Event.waitOnce

The callback is called once, only when all events are dispatched.

Unsubscribe from events

Each call to a subscribe method return a new subscriber object. It is then possible to use the off(events?: string | string[]): void method of the subscriber to choose which events to unsubscribe from. When passing the events argument, only those events are unsubscribed. Otherwise, all events are unsubscribed.

const subscriber = Zermatt.Event.on(["event-1", "event-2", "event-3", "event-4", "event-5"], (completedEvents) => console.log('Completed'));
// ...
subscriber.off('event-1') // remaining events: "event-2", "event-3", "event-4", "event-5"
subscribe.off(['event-2', 'event-3']) // remaining events: "event-4", "event-5"
subscribe.off() // no remaining event

Core Zermatt events

  • zermatt:kickoff. When the frontend Zermatt stack is first started.
  • zermatt:translation:init. When the translation layer is ready.
  • zermatt:module:init. When modules are loaded in Zermatt.
  • zermatt:form:key:init. When Zermatt has finished fetching the form key from the backend.
  • zermatt:init. Before the AlpineJS app is started (Alpine.start())
  • zermatt:ready. When Zermatt is ready.