An Alternative to Events – Attribute Passing Finishing Off

The last post looked at an alternative to events, in passing a reference to an attribute to the sub-component.

The problem at the moment is that we have ;

  1. A letter is typed in the AttributeSender message box
  2. This changes the attribute in the AttributeSender
  3. This changes the attribute in the AttributeSenderReceiver (because it is the same reference)
  4. The text is shown as the value on the formattedText

We need to change this to update the attribute only on the ‘Send’ button.

The first stage is on the AttributeSender.

Add a new attribute to hold the text entered:

<aura:attribute name="internalMessage" type="String" description="internal only"/>

also the input is changed to use this internal attribute

<lightning:input type="text" label="Message" class="slds-input" value="{!v.internalMessage}" placeholder="Enter your message..." />

Now any change to the text will update the internalMessage attribute

Now we can wire up our Send button

<lightning:button class="slds-button slds-button_brand" onclick="{!c.sendMessage}">Send</lightning:button>

sendMessage : function(component, event, helper) {
console.log("Send Message");
var thisMessage = component.get("v.internalMessage");


All this does is the get the text from the input and set the message attribute with this new message.  Again multiple ways to do this but using attributes makes this easy, clean and debuggable (if that is such a word).

This is half the work, now the receiver updates only when the Send button is added.  But each time any old receiver text is overwritten.

Change our formattedText to be the original receivedMessages

<lightning:formattedText value="{!v.receivedMessages}"/>

originally the events based handler was

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

but now we want to monitor an attribute for a change and then do an action – this is still done with the aura:handler code but slightly different syntax:

<aura:handler name="change" value="{!v.SenderMessage}" action="{!c.handleMessage}"/>

the code for the handleMessage is very similar to the event code except we can now look up the attribute from our current component not the event.

handleMessage : function(component, event, helper) {
var message = component.get("v.SenderMessage");

var currentmessage = component.get('v.receivedMessages');
currentmessage = currentmessage + '\r' + message;

Leave a Reply

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