Lightning web components Events

Let us discuss here how to use the lightning web component events to communicate between components. Lightning web components dispatch standard DOM events. Components can also create and dispatch custom events. Use events to communicate up the component containment hierarchy. Events in Lightning web components are built on DOM Events, a collection of APIs and objects available in every browser. we will be seeing here how to the events using the CustomEvent interface and publish-subscribe utility.

Create and Dispatch Events Using CustomEvent 

Let’s discuss here how to use to create events, using the CustomEvent interface. In Lightning web components, CustomEvent provides a more consistent experience across browsers, including Internet Explorer. It requires no setup or boilerplate, and it allows you to pass any kind of data via the detail property, which makes it flexible. Lightning web components implement the EventTarget interface, which allows them to dispatch events, listen for events, and handle events.
  1. To create an event, use the CustomEvent() constructor
    new CustomEvent('inptext', {
                detail: name
            });

     

  2. To dispatch an event, call the EventTarget.dispatchEvent()  method.
            this.dispatchEvent(selectEvent);
    

     

The CustomEvent constructor has one required parameter, which is a string indicating the event type. As a component author, you name the event type when you create the event. You can use any string as your event type. The below example shows how to use the CustomEvent constructor to fire the events and receive the events using the event object. In this example, we are firing the event from the eventsource component using the CustomEvent.Create a Lightning web component using the following SFDX command.

sfdx force:lightning:component:create --type lwc --componentname eventsource --outputdir force-app\main\default\lwc

Use the below eventsource.html code . in this code we have an input text field that will fire an event on onchange of the input text.

<template>
    <lightning-card title="Event Source">
        <div class="slds-m-around_medium">
            <lightning-input name="textVal" label="Enter Text" onchange={handleChange}></lightning-input>
        </div>
    </lightning-card>
</template>

use the below eventsource.js code and in this code, we have an handleChange function that will fire the event using the CustomEvent.

import {
    LightningElement
} from 'lwc';


export default class Eventsource extends LightningElement {
    handleChange(event) {
        event.preventDefault();
        const name = event.target.value;
        const selectEvent = new CustomEvent('inptext', {
            detail: name
        });
        this.dispatchEvent(selectEvent);
    }
}

Use the below eventsource.js-meta.xml code

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

Now create an event container component that will receive the events form the eventsource. create lightning web components using the below SFDX command

sfdx force:lightning:component:create --type lwc --componentname eventcontainer --outputdir force-app\main\default\lwc

Use the below eventcontainer.html code. To listen for events, use an HTML attribute with the syntax oneventtype Since our event type inptext, the listeners are oninptext  and call the handler function on oninptext events  as shown below

        <c-eventsource oninptext={handleSelect}></c-eventsource>

Use the below eventcontainer.html code

<template>
    <div class="slds-m-around_medium">
        You Enter {valueInp}
        <c-eventsource oninptext={handleSelect}></c-eventsource>
    </div>
</template>

Use the eventcontainer.js code.  Receiving components access the data in the detail property in the event listener’s handler function.

import {
    LightningElement,
    track
} from 'lwc';


export default class Eventcontainer extends LightningElement {
     @track valueInp;
     handleSelect(event) {

         const textVal = event.detail;
         this.valueInp = textVal;
         console.log('textVaal' + textVal);
     }
}

Use the below eventcontainer.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

The CustomEvent interface imposes no type requirements or structure on the detail property. However it’s important to send only primitive data. JavaScript passes all data types by reference except for primitives. If a component includes an object in its detail property, any listener can mutate that object without the component’s knowledge. This is a bad thing! It’s a best practice either to send only primitives, or to copy data to a new object before adding it to the detail property. Copying the data to a new object ensures that you’re sending only the data you want, and that the receiver can’t mutate your data.

Now if you see in the below image it shows the enter input data from the text box to container component. If you enter the text in the event source component, the CustomEvent will be fired and the same event details will be received at container component

 

 

Using publish-subscribe pattern

To communicate between components that aren’t in the same DOM tree, use a singleton library that follows the publish-subscribe pattern.In a publish-subscribe pattern, one component publishes an event. Other components subscribe to receive and handle the event. Every component that subscribes to the event receives the event. For example, if you add two components to a Lightning page in Lightning App Builder, use the pubsub module to send events between them. If you’re familiar with Aura, you may recognize that Aura application events follow the publish-subscribe pattern.

Please refer this link to get the publish-subscribe utility code.

Create a lightning web component using the below SFDX command.

sfdx force:lightning:component:create --type lwc --componentname publishsource --outputdir force-app\main\default\lwc

in this publish source component, we have an input text filed from where we are firing the event on input onchange events.

<template>
    <lightning-card title="Source" >
        <div class="slds-m-around_medium">
            <lightning-input type="text" onchange={handleChange} class="slds-m-bottom_small" label="Enter Text"></lightning-input>
        </div>
    </lightning-card>
</template>

Use the below publishsource.js code which will be publishing the event using publish-subscribe utility

import {
    LightningElement,
    wire
} from 'lwc';
import {
    CurrentPageReference
} from 'lightning/navigation';
import {
    fireEvent
} from 'c/pubsub';
export default class Publishsource extends LightningElement {
    @wire(CurrentPageReference) pageRef;

    handleChange(event) {
        fireEvent(this.pageRef, 'inputChangeEvent', event.target.value);
    }
}

In the above JavaScript file, we have two imports that are required to fire the events

import {
    CurrentPageReference
} from 'lightning/navigation';
import {
    fireEvent
} from 'c/pubsub';

Wire the current page reference using wire adapter as shown below

    @wire(CurrentPageReference) pageRef;

Fire the event using this below code .here inputChangeEvent is the event name.

        fireEvent(this.pageRef, 'inputChangeEvent', event.target.value);

use the below publishsource.js-meta.xml code

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

create a publish receive that will listen the events .create a lightning web component using the below SFDX command.

sfdx force:lightning:component:create --type lwc --componentname publishreceiver --outputdir force-app\main\default\lwc

Use the below publishreceiver.html code

<template>
    <lightning-card title="Target">

        {inpVal}
    </lightning-card>
</template>

Use the below publishreceiver.js code that will listen to the events using the life cycle callbacks

import {
    LightningElement,
    track,
    wire
} from 'lwc';
import {
    CurrentPageReference
} from 'lightning/navigation';
import {
    registerListener,
    unregisterAllListeners,
    fireEvent
} from 'c/pubsub';

export default class Publishreceiver extends LightningElement {
      @track inpVal;
      @wire(CurrentPageReference) pageRef;

      connectedCallback() {
          // subscribe to inputChangeEvent event
          registerListener('inputChangeEvent', this.handleChange, this);
      }

      disconnectedCallback() {
          // unsubscribe from inputChangeEvent event
          unregisterAllListeners(this);
      }

      handleChange(inpVal) {
          this.inpVal = inpVal;
      }
}

use the below publishreceiver.js-meta.xml code

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

Now you can able to see the event is firing from the source component which is handled by the target component as shown below.