Overview
Source: ./src/documentation/development/events.mdx
Events
Most OTTO Components are interactive and provide custom and generic events.
Custom events are specific to each component, while generic events like oc-property-change are common to all interactive components.
Skip to:
Generic events
The generic oc-property-change event throws whenever a property value of a component has changed.
The payload of the event contains details about the updated property name, the old value, and the new value.
For example, when a visibility property of a component changes, the component throws an oc-property-change event.
The returned event object has the following properties:
{
"detail": { // The payload of the event. It contains the following properties:
"myExampleProperty": { // The name of the property that has changed.
"current": "", // The new value of the property
"previous": "" // The old value of the property
}
}
}
Custom events
All custom events have the prefix oc- to avoid any confusion or overlaps.
Examples are: oc-open, oc-click, and oc-load.
Use events
While all other events do bubble up, the oc-property-change event does not bubble up through the DOM tree.
To listen for the oc-property-change event, use the component-specific event type, in this case, OcExampleComponentV1Events["oc-property-change"].
Here is an example of how to listen to the oc-property-change event:
import { OcExampleComponentV1Events } from "@otto-ec/otto-components/example-component";
const myExampleComponent = document.querySelector("oc-example-component-v1");
const myExampleHandler = (e: OcExampleComponentV1Events["oc-property-change"]) => {
/* * your code */
ev.detail.myExampleProperty; // The name of the property that has changed.
ev.detail.myExampleProperty.current; // The new value of the property.
ev.detail.myExampleProperty.previous; // The old value of the property.
};
myExampleComponent.addEventListener("oc-property-change", myExampleHandler);
Events in a JS application
Listen to events in a JavaScript application by using the addEventListener method:
const button = document.querySelector("oc-button-v1");
button.addEventListener("click", () => {
console.log("Button clicked");
});
To stop the event propagation, call event.preventDefault():
const button = document.querySelector("oc-button-v1");
button.addEventListener("click", (event) => {
ev.preventDefault();
});
Events in a Svelte application
To listen to events in a Svelte application, use the on: directive.
This causes two accessibility warnings, which you can ignore by adding the svelte-ignore comment:
<script>
export const somehandleClick = () => {
// your way to handle the click
};
</script>
<!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<oc-button-v1 on:click={somehandleClick}>Click me!</oc-button-v1>