2.3 Handle ui elements in client side controller

In our previous example we generated a lightning component which handles click events from two buttons. If you are an experienced developer, you might have already noticed that the code is not very DRY (Don’t repeat yourself). Both buttons serves almost the same functionality, why do we need to duplicate the code?

At that time, we didn’t know how to read client side data in the controller, so I wrote the code in that way. In this post, I will show you how to read and manipulate data from the view.

The Code

First let’s modify the javascript controller of SimpleButtonCmp into below code:

    handleClick : function(component, event, helper) {
        var buttonClicked = event.getSource(); //the button
        var buttonLabel = buttonClicked.get("v.label"); //the button's label; 
        var customerName = '';
        if(buttonLabel.indexOf("Mary") > -1) {
            customerName = "Mary";
        } else {
            customerName = "Clark";
    	component.set("v.customerName", customerName);
        buttonClicked.set("v.label", buttonLabel + " clicked");

Then let’s change your component code to be:

<aura:component >
	<aura:attribute name="customerName" type="String"/>
	<div> Hello {!v.customerName}!</div>
	<ui:button label="Choose Mary" press="{!c.handleClick}"/>
	<ui:button label="Choose Clark" press="{!c.handleClick}"/>

Try this in your org.

A little bit explanation

You may have noticed. This code has a bug. After clicking the button multiple times, there are multiple ‘clicked’ appended after each button. Like below:

You can think about how to fix it. Actually, this is the exercise for this post.

In each action handler function, there is an event parameter. By using that parameter we can access the button clicked. Then we can use buttonClicked.get() and buttonClicked.set() to fetch and manipulate the functionality of the event button.


Think about how to fix the bug in this post. Please note that global variable is not allowed in controller file.

Hint: use another attribute to hold the value.

Next Post

2.4 Use init handler to initialize the page

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

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