Custom events
Sometimes you need your frontend to react to certain events as they occur at runtime.
For example, you may find yourself needing to implement a feature that removes items that cannot be checked out with topi from a customer's cart (after asking for consent, of course).
To achieve that, you'd 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)
Let's learn how this works.
Reacting to custom events
1. Register an event listener and handler
The topi Elements library comes with its own implementation of addEventListener
that can be used to register an event handler:
const topi = new TopiElements({
// ...
});
const handler = (event) => {
console.log(event);
};
topi.addEventListener("cartCannotCheckout", handler);
You've successfully registered a handler callback with topi for a custom event!
Now whenever the event fires at runtime, your callback will be 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.
So, your handler will be receiving a custom event, which you'll need to parse for the payload like so:
const handler = (event) => {
const payload = event.detail;
};
3. Cleaning up on page navigation
Do not skip this step!
Typically, you'd want a specific callback to be invoked when an event occurs only on a specific page.
Back to the earlier example of "remove items from cart that cannot be checked out." In this case, you'd only want the callback to be active when the shopper is on the last step of your checkout flow and not in any other step. Certainly not when they're browsing products!
To remove the event listener, you can invoke a method on the object that is returned when we added the event listener in step 1:
const listener = topi.addEventListener("cartCannotCheckout", handler);
listener.abort();
Under the hood, adding an event listener via topi will return an instance of the web standard AbortController
interface. That instance is connected to the event listener that was added, so when you call listener.abort()
, you are effectively doing the equivalent of removeEventListener(...)
, just easier.
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
.