Sunday, 21 July 2024

Event Delegation in LWC

 Event delegation is a pattern in javascript where a single event listener is added to a parent element

to manage events for its child elements.Instead of adding event listeners to each individual child elements,

event delegation takes advantage of event bubbling,which allows the parent element to handle events for its descendants.


In LWC, event delegation can simplify code,improve performance and reduce memory consumption by minimizing the number of event listeners.


ex :


<template>

<div class="contact-list" onclick={handleContactClick}>

 <template lwc:if={contacts.data}>

     <template for:each={contacts.data} for:item="contact">

        <div key={contact.Id} data-id={contact.Id} class="contact-item">

{contact.Name}

</div>

     </template>

</template>

</div>

</template>


export default class ContactList extends LightningElement {

    @wire(getContactList) contacts;


    handleContactClick(event) {

        // 1. Identify the target element that triggered the event

        const target =event.target;

        // 2. Check if the target is a contact item

        if(target.classList.contains('contact-item')){

   // 3. Retrieve the Contact id from the target

   const contactId=target.dataset.id;

   // 4. Perform the described action with the contact id

    }

}


Note :

Utilize event delegation to minimize the number of event listeners in your application.

By setting a single listener on a parent element and checking the event. target property, you can handle events from multiple child elements efficiently.


No comments:

Post a Comment