Tuesday, December 20, 2022

Communicate with Events

Lightning web components dispatch standard DOM events. Components can also create and dispatch custom events. Use events to communicate up the component containment hierarchy. For example, a child component, 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.


Tip To communicate down the component containment hierarchy, pass properties to the child via HTML attributes, or call its public methods. To communicate between components, use Lightning message service or a publish-subcribe utility.
  • Create and Dispatch Events
    Create and dispatch events in a component’s JavaScript class. To create an event, use the CustomEvent() constructor. To dispatch an event, call the EventTarget.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

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC)

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC) Introduction: Salesforce Lightning Web ...