Events are used to communicate up the component hierarchy and LWC dispatches standard DOM events. Several usages apply:
To create an event, use the CustomEvent()
constructor.
on
, as you will end up with this: <c-my-component **onon**message={handleMessage}>
.To dispatch a custom event, call the EventTarget.dispatchEvent()
method. LWCs implement the EventTarget
interface, which allows them to dispatch events, listen for events, and handle events.
In the following Javascript code you can see both calls together, creating and dispatching a custom event (with no data associated to the event).
When a user clicks any of the 2 buttons, the onclick
standard handler is listening the standard event. As a response to it, the custom handlers previousHandler
or nextHandler
are invoked.
Those 2 handlers create and dispatch custom events previous
and next
respectively.
<template>
<lightning-layout>
<lightning-layout-item>
<lightning-button
label="Previous"
icon-name="utility:chevronleft"
<!-- When the user clicks the standard click event is fired and a handler is invoked -->
onclick={previousHandler}></lightning-button>
</lightning-layout-item>
<lightning-layout-item flexibility="grow"></lightning-layout-item>
<lightning-layout-item>
<lightning-button
label="Next"
icon-name="utility:chevronright"
icon-position="right"
<!-- When the user clicks the standard click event is fired and a handler is invoked -->
onclick={nextHandler}></lightning-button>
</lightning-layout-item>
</lightning-layout>
</template>
import { LightningElement } from 'lwc';
export default class Paginator extends LightningElement {
previousHandler(event) {
//firing a new custom event
this.dispatchEvent(new CustomEvent('previous'));
}
nextHandler(event) {
//firing a new custom event
this.dispatchEvent(new CustomEvent('next'));
}
}
To pass data set a detail
property in the CustomEvent
constructor.
// contactListItem.js
import { LightningElement, api } from 'lwc';
export default class ContactListItem extends LightningElement {
@api contact;
selectHandler(event) {
// Prevents the anchor element from navigating to a URL.
event.preventDefault();
// Creates the event with the contact ID data.
const selectedEvent = new CustomEvent('selected', { detail: this.contact.Id });
// Dispatches the event.
this.dispatchEvent(selectedEvent);
}
}
CustomEvent
called selected
.detail: this.contact.Id
, which is the ID of the selected contact.