Skip to main content

Custom events

Sometimes your frontend needs to react to events as they occur at runtime.

For example, you might build a feature that removes items from a customer's cart when they cannot be checked out with topi.

For that, you need topi Elements to:

  • invoke a callback you registered when it detects that the cart cannot be checked out (the event), and
  • provide a list of items in the cart that cannot be checked out (the data)

Here's how this works.

Reacting to custom events

1. Register an event listener and handler

topi Elements has its own implementation of addEventListener for registering an event handler:

const topi = new TopiElements({
// ...
});

const handler = (event) => {
console.log(event);
};

topi.addEventListener("cartCannotCheckout", handler);

You've registered a handler callback with topi for a custom event.

Whenever the event fires at runtime, your callback is invoked with event-specific arguments.

2. Extract the event detail

Because topi Elements uses the web standard CustomEvent interface under the hood, the event that is dispatched has all the properties of the Event interface as well as a detail property where custom payloads are stored.

Your handler receives a custom event. Parse it for the payload like this:

const handler = (event) => {
const payload = event.detail;
};

3. Cleaning up on page navigation

warning

Do not skip this step!

Often you want a callback to run only when an event occurs on a specific page.

Take the earlier example of removing items from the cart that cannot be checked out. You'd want the callback active only when the shopper is on the last step of your checkout flow, not on any other step, and not while they're browsing products.

To remove the event listener, call a method on the object returned when you added the listener in step 1:

const listener = topi.addEventListener("cartCannotCheckout", handler);

listener.abort();

Adding an event listener via topi returns an instance of the web standard AbortController interface. That instance is connected to the listener you added, so calling listener.abort() is the equivalent of removeEventListener(...).

List of custom events

"cartCannotCheckout"

This event is fired if the following conditions are met:

  • You've set some items using topi.cartItems = [...]
  • One or more items cannot be checked out

The callback will be invoked with a list of sellerProductReference. You can then retrieve the reference (product ID) of the item(s) that cannot be checked out with sellerProductReference.reference.