Describe the use cases for Lightning Web Component events.

After studying this topic, you should be able to:

  • Describe how to create and handle component and application events.
  • Identify whether a component or application event should be used to meet specific user interface requirements.
  • Identify how events are used for communication in Lightning web components.
  • Describe how to define event propagation behavior in Lightning web components.

Table of Contents

  • Introduction
  • Aura Component Events
  • Lightning Web Component Events
  • Lightning Web Component Event Example
  • Event Propagation in Lightning Web Components
  • Dynamic Interactions
  • Scenarios and Solutions

Introduction

  • The Lightning Component framework allows Aura components to communicate with each other using component and application events. Events can be fired by a particular component and handled by another component. Each type of event has certain use cases.
  • Lightning web components, which are custom HTML elements built using HTML and modern JavaScript, are capable of firing and handling both standard and custom events.
  • What Events are and the different types of events will be covered on this page in order to determine the event type to use in a given scenario.

Aura Component Events

  • Events: The Lightning Component framework uses event-driven programming. Lightning Aura components can communicate with each other using events. An event may or may not be triggered by user interaction
    • Event Configuration: Events can be configured to relay data within the containment hierarchy or to all components in the application. Events are fired from JavaScript controller actions. Components with registered event handlers can respond to the events
    • Event Types: Two types, both fired from an instance of a component.
      • Component Event: can be handled by the component that fired the event or by a component in the containment hierarchy
      • Application Event: can be handled by any component that has a handler for the event
  • Component Events: A component event can be handled by all the components in the containment hierarchy as long as they have handlers configured to handle the event
    • Containment Hierarchy: refers to a tree of components that has a top-level container as its root component. When an event is triggered, all components within the containment hierarchy are notified
    • Component Event Propagation: How an event is propagated in the containment hierarchy depends on the phase that is configured in the event handler. There are two types of phases available for component events, namely, Bubble and Capture
      • Bubble Phase: The default phase used by a component event is the bubble phase, which behaves in a bottom-up manner. When an event is fired, 1) source component handles the event first. 2) parent component, 3) grandparent, and then each remaining component all the way up until the root component
      • Capture Phase: The order of the event propagation in the capture phase behaves in a top-down manner. 1) root component gets to handle the event first, 2) and the propagation traverses down the containment hierarchy until it reaches the source component
    • Stopping Event Propagation: Event propagation can be terminated any time the stopPropagation method is executed in an event handler
  • Component Event Configuration: An Aura component can be registered to an event using the <aura:registerEvent> tag. To respond to the event, the <aura:handler> tag can be used

  • Application Events: An application event follows a publish-subscribe model where the event is fired from a source component and all components in the application are notified
    • Application Event Propagation: An application event has three types of phases: Bubble, Capture, and Default.
      • The order of the event propagation for the bubble and capture phases in an application event is the same as the component event.
      • When using the default phase, the event handlers are invoked in a non-deterministic order. It does not follow the same propagation rules related to the component hierarchy as the capture and bubble phases. Instead, the event is broadcast to all components in the application
    • Event Propagation Considerations: When an event is terminated by a handler using the stopPropagation method, the component of that handler becomes the root node used in the default phase.
      • When a handler cancels the default behavior of an event using the preventDefault method, it prevents the rest of the event handlers from executing in the default phase

  • Choosing Event Type: It is best practice to always use component events whenever applicable
    • Application Event Flexibility: An application event may be flexible as it is not subject to the component’s hierarchical setup for it to successfully relay events, but this behavior may affect performance in certain use cases since the event is broadcast to all the components in the application
    • Application Level Events: Only use an application event for events that should be handled at the application level or when a component needs to communicate with another component that does not belong to the containment hierarchy of the source component
    • Using Component Events: Using a component event is more efficient and allows better control and focus with regard to the components to which it relays the event data

Lightning Web Component Events

  • Events in Lightning Web Components: can be fired and handled in Lightning web components:
    • DOM Events: Lightning Web Components do not use Component and Application Events. Instead, they use standard browser DOM events (or custom events) for communicating up the containment hierarchy
    • Relaying Events: To relay the event down the containment hierarchy, properties can be passed from parent to child components via HTML attributes, or public methods of the nested component can be called
    • Publish-Subscribe: To propagate the event between containment hierarchies, Lightning Web Components use the same Application Event publish-subscribe model, typically with the use of a “pubsub” module
  • Creating and Dispatching Events: In a Lightning web component, a custom event can be created by calling the CustomEvent() constructor
    • Custom Event: It can be dispatched by calling the EventTarget.dispatchEvent() method. A string that indicates the event type is required when creating a custom event
    • Some considerations:
      • Detail Property: In addition to the event type, one can pass data to the event by specifying an object that includes the detail property in the CustomEvent() constructor.
        • This detail property is used for passing custom value
        • Important to send only primitive data via detail, or send a copied object to prevent the receiver from mutating the object data. The reason for this is in JavaScript, all data types except primitives are passed by reference
      • Naming Standard: To conform to the DOM event standard, the event type should use underscores to separate words and have no uppercase letters or spaces
  • Handling Events: To handle an event, an event listener can be attached declaratively and programmatically
    • Attach Declaratively: To attach an event listener declaratively in the HTML markup, an event handler function must be specified using an attribute named oneventtype.
      • For example, to handle an event named message dispatched by a child component in the parent component, an attribute named onmessage with an event handler can be added to the child component in the template of the parent component
    • Attach Programmatically
      • To attach an event listener programmatically in the JavaScript controller, the addEventListener() method can be used.
      • Or, To attach an event listener to an element within the shadow boundary, this.template.addEventListener() can be used.
      • To attach an event listener to an element that the template does not own, this.addEventListener() can be used
    • Event Target
      • The Event.target property can be used to get a reference to the component that dispatched the event. It is typically used to listen for changes to input fields using the onchange event

Lightning Web Component Event Example

  • Example screenshots below shows how to create and dispatch an event in a child component and handle it in its parent component

  • This image shows the client controller of the child component

  • Markup of the parent component below that handles the event fired from the child component is shown below

  • Markup below shows the client controller of the parent component

  • The parent component updates its property values with data of the event that was fired from the child component

Event Propagation in Lightning Web Components

  • Event Propagation in Lightning Web Components: Parent and child Lightning web components can communicate through events using the bubbling phase only
    • Bubble Up: An event can bubble up through the DOM, moving to the component’s parent, and then grandparent, and so on
      • While creating an event, event propagation behavior can be defined using two properties, namely, bubbles and composed
    • Event Bubbles: The Event.bubbles property defaults to false and is used to indicate whether the event bubbles up through the DOM
    • Event Composed: The Event.composed property defaults to false and is used to indicate whether the event can pass through the shadow boundary
    • Event Target: this property refers to the element that dispatches the event
      • The Event.currentTarget property refers to the element to which the event handler is attached
      • The Event.composedPath() method can be used to get an array of elements on which an event handler is invoked as the event traverses through the DOM
  • Defining Event Propagation Behavior: While creating a custom event, a configuration can be passed to indicate whether the event should bubble up through the DOM and/or cross the shadow boundary
    • bubbles:false, composed:false: default configuration is bubbles:false and composed:false.
      • Means that the event does not bubble up through the DOM and does not cross the shadow boundary. It can only be handled by the component that dispatches the event
    • bubbles:true, composed:false: allows bubbling up the event through the DOM
      • Typically used to create and dispatch an internal event or send an event to a component’s grandparent when a component is passed into a slot
    • bubbles:true, composed:true: can be used to bubble up an event through the DOM, cross the shadow boundary, and continue bubbling up through the DOM to the document root
    • bubbles:false, compsed:true: NOT SUPPORTED by Lightning web components

  • Example below shows how to define event propagation behavior and how it affects the event

  • Shown below is the client controller of the Lightning web component

  • This example uses an event that can only be handled by the same component that invoked it

  • Non-Composed Event: A custom even where the composed property is not specified will not be visible outside of the shadow root from which they were dispatched

  • Communication Across the DOM: Lightning web components that are not in the same DOM tree can communicate with each other using the Lightning Message Service or the pubsub module:
    • Lightning Message Service: The Lightning Message Service (lightning/messageService) can be used to communicate between components within a single Lightning page or across multiple pages. It supports Aura components, Lightning web components, and Visualforce pages in any tab or pop-out window in Lightning Experience
    • Pubsub Module: The pubsub module can be used in containers that do not support Lightning Message Service. It utilizes the publish-subscribe pattern: one component publishes an event, while other components subscribe to receive and handle the event

Dynamic Interactions

  • Dynamic Interactions enable Lightning web components to fire and expose custom events that other components on the same Lightning page can respond to

  • Exposing Events to Target Components: Target components can respond to custom events explicitly exposed by source components. To expose events, the event and schema subtags are added to a source component’s configuration file

  • Firing an Exposed Event: No programmatic configurations specific to Dynamic Interactions are added in the JavaScript controller of the source component. The event is fired normally as a custom event

  • Example Target component: following shows an example Lightning web component that can be defined as a target component

  • Defining a Target Component: Lightning App Builder is required to select the target components for exposed events of a source component. Dynamic Interactions is supported only on Lightning App pages

  • Interaction Details Tab: Clicking on the Add Interactions button opens up the Interaction Details tab for the selected event

  • Dynamic Interaction Example: When a contact is selected from the list, the source component fires the custom event that contains the record id of the contact and causes the recordId public property of the target component to be changed

Scenarios and Solutions

Reference FoF Slides