c-todo-item
, dispatches an event
to tell its parent, c-todo-app
, that a user selected
it.Events in Lightning web components are built on DOM Events, a collection of APIs and objects available in every browser.
The DOM events system is a programming design pattern that includes these elements.
- An event name, called a type
- A configuration to initialize the event
- A JavaScript object that emits the event
To create events, we strongly recommend using the CustomEvent
interface. In Lightning web components, CustomEvent
provides a more consistent experience across
browsers. It requires no setup or boilerplate, and it allows you to pass any kind of data via
the detail
property, which makes it flexible.
Lightning web components implement the EventTarget
interface, which allows them to dispatch events, listen for events, and handle events.
- Create and Dispatch Events
Create and dispatch events in a component’s JavaScript class. To create an event, use theCustomEvent()
constructor. To dispatch an event, call theEventTarget.dispatchEvent()
method. - Handle Events
There are two ways to listen for an event: declaratively from the component’s HTML template, or programmatically using an imperative JavaScript API. It’s better to listen from the HTML template since it reduces the amount of code you have to write. To handle events, define methods in the component’s JavaScript class. - Configure Event Propagation
After an event is fired, it can propagate up through the DOM. To understand where events can be handled, understand how they propagate. - Communicate Across the DOM
There are two ways to communicate between components that aren’t in the same DOM tree. Use Lightning message service (lightning/messageService
), or use a singleton library that follows the publish-subscribe pattern. - Events Best Practices
We recommend following these best practices when working with events.
No comments:
Post a Comment