Events in Lightning web components

component events in lwc

In this post, we are going to discuss about Events and how to use it in lightning web components.

Events are used to establish communication between two or more components. Events in lwc are built on DOM events, a collection of APIs and objects available in every browser.

Like in Aura, we also have different types of events – component and application events but they are not differentiated by type in lwc.

Here, we are going to discuss how to use components events in LWC

If the components are in containment hierarchy (which are related each other) then we use component events. So something like this. A, B, C.

Salesforce official documentation

Events are propagated in two phases, capture and bubble. When the event is fired, event propagtion starts from root component (ultimate parent) in hierarchy – this is called capture phase.

Once it reaches the component (where the event actually fired), it starts bubbling to root again – this is called bubble phase. Most of our components that we write in lwc are work in bubble phase.

How to create and fire an event in lwc ?

As said earlier, events in lwc are built on DOM events. we can create in different ways but one of the recommended ways is to create using CustomEvent interface. We use CustomEvent constructor to name an event and pass the parameters to it. Let see how to do this.

// Creates the event with the contact ID data.
const alertEvent = new CustomEvent('alert', { detail: this.contact.Id });
// Dispatches the event.
this.dispatchEvent(alertEvent);

In this example,
alert is the name of the event.
detail object is the data that we want to pass in this event.

To fire an event, we use dispatchEvent method in EventTarget interface. Lightning web components implements this interface, which allows to fire, listen and handle the events. We need to pass the created event as a parameter to dispatchEvent method.

How to handle an event ?

Now, we know how to create events. Lets see how to handle them in parent components.

We have different ways to listen for an event such as Inline event handlers, addEventListener methods to listen for an event. One of the easiest and recommened way in lwc is to use inline event handlers as they are declared directly in component HTML template.

<c-child onalert={handleAlert} ></c-child>

In this example, we are handling an alert event fired from child using inline event handlers. Inline event handlers are declared as HTML attributes to listen for an event and add handlers to process the event. In this case, we use handleAlert function to process the event.

handleAlert(event){
   // name is a local property
   this.name = event.detail;
}

By default all event handlers have an event object as a parameter, In this example that object is defined with name – event. We can have any name (event, eve, e & etc) to it. To access the paramters that are set to event object, we use dot operator. In this example, it is event.detail

Thats it, we now know how to create, fire and handle an event.

You can see a live example in this trailhead playground snippet. Click HERE.

But still we are not successful in propagating the event to root i.e. outside the shadow boundary. To make our event bubble and pass through shadow boundary, we need to set properties such as bubble and composed in CustomEvent constructor.

What are bubbles and composed ?

bubbles: A Boolean value indicating whether the event bubbles up through the DOM or not. Defaults to false.
composed: A Boolean value indicating whether the event can pass through the shadow boundary. Defaults to false.

Event propagation behaviour works using these two properties. To explain this in detail, i have created a project in playground here.

In the above example, we have 3 components – grandparent, parent and child. When the event is fired in child, the event will be bubbled up and can be handled only at that component. To reach the event till root component (grandparent in above example), we need to set these two additional properites like below

new CustomEvent('alert', { bubbles: true, composed: true, detail: 
                                                         element.value }));

In this way the event fired in child component can be bubbled to root through parent and grandparent.

In short, if we have multiple components in hierarchy (more than 2), then we need to set these two properties to propagate the event till root.

What if we want to stop propagation in the middle ?

We use event.stopPropagation() method to stop the propagation in containment hierarchy. If we do not use this, then the event follows the applicable propagation.

Fully working example can be found in playground. Click here.

Thats it about component events in lwc.

We are going to discuss about how to work between components – which are not in containment hierarchy, basicaly application events in other post.

Resources:

Communication with events
CustomEvent from MDM

Please follow and like us:
error

Be the first to comment

Leave a Reply

Your email address will not be published.


*