Skip to content

Event Bus

One of the buses used in storefront to handle application events in a clean and robust manner. Unlike the Command Bus and Query Bus the Event Bus broadcasts events to multiple listeners without expecting any return value, always returning undefined.

Each event can have multiple listeners at the time.

Event Bus Methods

The Event Bus utilizes methods that allow to handle events depending on your needs.

  • on - allows to listen to the event similarly to how addEventListener works for DOM events.
  • once - allows to listen to an event only until it fires once. Then the listener is being removed.
  • off - allows to remove a listener from the event similarly to how removeEventListener works for DOM events.
  • offAll - allows to remove all listeners from the given event.
  • emit - allows to emit a given message.
  • getListeners - allows to get all listeners of given message.
  • getListenersCount - allows to get the count of all listeners of given message.

Example

To listen to any event emitted by the Event Bus you can use the on method:

useStorefront(async (storefront) => {
    storefront.eventBus.on('example-event', () => {
        console.log('Listening to the event...')
    });
});

Example

To remove a listener from any event of the Event Bus you can use the off method:

useStorefront(async (storefront) => {
    function myFunction(event) {
        console.log('Event:', event.name);
    }

    storefront.eventBus.on('event-name', myFunction);

    storefront.eventBus.off('event-name', myFunction);
});

Example

In this example we emit a message using the Event Bus and listen to it:

useStorefront(async (storefront) => {
    function myFunction(event) {
        console.log('Got the event exampleField:', event.body.exampleField)
    }

    storefront.eventBus.on('my-event', myFunction);

    storefront.eventBus.emit({
        name: 'my-event',
        type: 'event',
        body: {
            exampleField: 'this is my event'
        }
    });
});

Example

To get all listeners for a given message using the Event Bus you can use the getListeners method:

useStorefront(async (storefront) => {
    const listeners = storefront.eventBus.getListeners('my-event');

    console.log('listeners of my-event:');

    listeners.forEach((listener) => {
        console.log('listener:', listener)
    })
});