2.4 Use init handler to initialize the page

In our previous examples, when loading the page, the customer name is default to be blank. It makes the text very weird when loading: Hello ! .

To make it more user-friendly, we should set up a default value for customerName attribute. There is a very simple way doing so. We can simply change the attribute line of code into:

<aura:attribute name="customerName" type="String" default="Mary"/>

For our current example, this perfectly resolves the issue. If we assumes our default customer is Mary. What if we want a little bit logic to decide who is our default customer? Say if we want to flip a coin to decide whether we should choose Mary or Clark to be our default customer?

We need to use a initial handler in that case. Below is the sample code.

The code

First, our SimpleButtonCmp code:

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

Then the controller code:

    doInit: function(component, event, helper) {
        var initCustomerName;
        var flipCoinValue = Math.floor((Math.random() * 2) + 1);
        if(flipCoinValue == 1) {
            initCustomerName = "Mary";
        } else {
            initCustomerName = "Clark";
        component.set("v.customerName", initCustomerName);

    handleClick : function(component, event, helper) {

A little bit explanation

All the magic happens at the line:

<aura:handler name="init" value="{!this}" action="{!c.doInit}" />

We will explain this more when we introduce events. For now, we just need to remember this is the standard format of introducing a init method. And the code in controller’s doInit() method will be executed when the page loads.

In the doInit() method in the Javascript controller, we simply flipped a coin and used the result to display relevant customer’s name as the default value.

Next Post

2.5 Handle events for regular html elements

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 *