The Smaller Component Event

The little brother of the application event is the component event.

This post used the idea of two separate components to do an application event between them. Component events are designed to Bubble up from a sub-component.

This is a one column, one main component with a sub sender component.  The event goes from the sender component to the main component.  The code is very similar to the previous post.

Setup

  1. Create a lightning control called AllInOneSenderReceiver this will have implements=”flexipage:availableForAllPageTypes” so that it can be on a lightning app page
  2. Create a lightning control called AllInOneSender
  3. The AllInOneSender has the same code for the presentation of the message box and Send button

<article class="slds-card">
<div class="slds-card__header slds-grid">
<header class="slds-media slds-media_center slds-has-flexi-truncate">
<div class="slds-media__body">
<h2>
<span class="slds-text-heading_small">Sender</span>
</h2>
</div>
</header>
</div>
<div>
<lightning:input type="text" label="Message" class="slds-input" value="{!v.message}" placeholder="Enter your message..." /><br/>
<lightning:button class="slds-button slds-button_brand" onclick="{!c.sendMessage}">Send</lightning:button>
</div>
</article>

Event

Create a lightning event called CompEvntMessage

This is exactly the same as the EvntMessage on the application event example except the type=”COMPONENT”.

In the AllInOneSender register to use the event


<aura:registerEvent name="sendMessage" type="c:CompEvntMessage"/>

In the sendMessage controller code the code to send a component event is quite different to the application code:


var compEvent = component.getEvent("sendMessage");
compEvent.setParams({ "message": thisMessage });
compEvent.fire();

AllInOneSenderReceiver

To add the AllInOneSender component to this component add


<c:AllInOneSender />

Then the code is as before


<aura:attribute name="receivedMessages" type="String" default="Messages will appear here"/>

<article class="slds-card">
<div class="slds-card__header slds-grid">
<header class="slds-media slds-media_center slds-has-flexi-truncate">
<div class="slds-media__body">
<h2>
<span class="slds-text-heading_small">Receiver</span>
</h2>
</div>
</header>
</div>
<div>
<lightning:formattedText value="{!v.receivedMessages}"/>
</div>
</article>

To handle the event use:


<aura:handler name="sendMessage" event="c:CompEvntMessage" action="{!c.handleMessage}"/>

The handleMessage controller code is the same

To summarise on the sending side we register to send the event


<aura:registerEvent name="sendMessage" type="c:CompEvntMessage"/>

on the receiver side we have a handler to deal with the message


<aura:handler name="sendMessage" event="c:CompEvntMessage" action="{!c.handleMessage}"/>

Leave a Reply

Your email address will not be published.