Handling Events

By in
414
Handling Events

The HTML template for the component can be used declaratively to listen for events, or programmatically using an imperative JavaScript API. Since less code needs to be written, it is better to listen from the HTML template. Create methods in the component’s JavaScript class to handle events.

HTML Template Declaratively or Programmatically
Image Source: Trailhead by Salesforce

 

Attaching an Event Listener Declaratively

You need to declare the listener in markup in the template of the owner component, in this example, c-parent.

 

<!– Wgparent.html –>

<template>

<c-wg-child onnotification={handleNotification}></c-child>

</template>

 

You need to define the handler function, in this example handleNotification, in the c-wg-parent JavaScript file.

 

// Wgparent.js

import { LightningElement } from ‘lwc’;

export default class WgParent extends LightningElement {

handleNotification(){

// Code runs when event is received

}

}

 

Attaching an Event Listener Programmatically

You need to define both the listener and the handler function in the c-wg-parent JavaScript.

 

// Wgparent.js

import { LightningElement } from ‘lwc’;

export default class WgParent extends LightningElement {

constructor() {

super();

this.template.addEventListener(‘notification’, this.handleNotification);

}

handleNotification = () => {};

}

 

The browser ignores duplicate listeners that are added to the same element repeatedly.

You can decide to inline the handleNotification code in the addEventListener() call if the event listener is left in place.

 

For example,

this.template.addEventListener(‘notification’, evt => {

console.log(‘Notification event’, evt);

});

 

An event listener can be added using one of two syntaxes. One is to add an event listener to an element inside the shadow boundary of a component, and one is to add an event listener to an element that is not owned by the template, such as an element that is passed into a slot.

Use the template to add an event listener to an element inside the shadow boundary or you could choose to add an event listener to an element that a template doesn’t own for that you can call addEventListener directly.

 

Conclusion

In this way, you can listen for events in the lightning web component using any one of the above syntaxes but in most cases, it’s easier to use the declarative approach.

 

Additional Resources

Cover Photo by Oskar Yildiz on Unsplash

Leave a reply

Your email address will not be published. Required fields are marked *