Day: January 2, 2018

Lightning Attributes unbound vs bound bindings expressions

Introduction:-

In this blog, I am going to explain how to use salesforce attribute unbound vs bound binding. Attributes are key parts of a web component-based framework like lighting, Polymer and react etc which are used to communicate or exchange data between components. You can think it like a member variable in Java. Here is the example of attributes

<aura: attribute name="whom" type="String" default="world" required="true"/>

Now if you see the below components having an attribute name message which is referred in the component by using {!v.message} with {!} expression know as the bounded expression. Salesforce supports two types of expression bounded and unbounded to pass the attribute values.

<aura:component >
<aura:attribute type="String" name="message" default="Welcome to salesforce" description="Simple Message " />
<aura:attribute type="Account" name="acc" default="{'sObjectType':'Account', 'Name':'SFDC'}" description="Account attribues "/>
<aura:attribute type="List" name="types" default="['Salesforce', 'force.com', 'Lightning']" description="Collection type" />
<div>
{!v.message}
</div>
<div>
{!v.acc.Name}
</div>

<div>
{!v.types[0]}
</div>
</aura:component>

Expression Binding: –

Salesforce supports two type of binding expression in Salesforce namely bounded and Unbounded.  The two forms exhibit different behaviors for data binding and updates when you pass an expression from a parent component to a child component that it contains.

{! Expression} (Bound Expressions)

Data updates in either component are reflected through bi-directional data binding in both components. Similarly, change notifications are triggered in both the parent and child components. Means if you update any attributes in parent components those changes will be updated to child component attributes.

{#Expression} (Unbound Expressions)

Data updates behave, as you would expect in JavaScript. Primitives, such as String, are passed by value, and data updates for the expression in the parent and child are decoupled.Objects, such as Array or Map, are passed by reference so changes to the data in the child propagate to the parent. However, change handlers in the parent won’t be notified so it will not be re-rendered. The same behavior applies for changes in the parent propagating to the child.

Bi-directional data binding is expensive for performance and it creates hard-to-debug errors due to the propagation of data changes. So its recommend using the {#expression} syntax instead when you pass an expression from a parent component to a child component unless you require bi-directional data binding.

Here is the simple Component ChildExp1.cmp with bounded expression

<aura:component >
    <!-- Primitive type Attributes  and are passed by value, and data updates for the expression in the parent and child are decoupled. -->
    <!-- Objects, such as Array or Map, are passed by reference -->
    
    <h6> <b>Inner Component</b></h6> <br/>
    <aura:attribute name="welcomemessage" type="String" default="Welcome to Child Component"/>
    <aura:attribute name="acc" type="Account" default="{'sObjectType':'Account' , 'Name':'Child Account '} "/>
    <aura:attribute name="booleanValue" type="Boolean"/>
    <aura:attribute name="numberValue" type="Double"/>
    <aura:attribute name="stringValue" type="String"/>
    <aura:attribute name="listValue" type="List" default="['red', 'green', 'blue']"/>
    <aura:attribute name="mapValue" type="Map" default="{ a: 'label1', b: 'label2' }"/>
    <div>
      <b>  Child Component Welcome Message : {!v.welcomemessage}</b>
    </div>
    <div>
       <b> Child Component Account Name : {!v.acc.Name}</b>
    </div>
    <div>{!v.booleanValue}</div>
    <div >{!v.numberValue}</div>
    <div >{!v.stringValue}</div>
    <div >
        <aura:iteration aura:id="box" items="{!v.listValue}" var="message" indexVar="index">
            {!index}:{!message}<br/>
        </aura:iteration>
    </div>
    <br/>
    <div >{!v.mapValue}</div>
    <p><ui:button label="Update Child Component " press="{!c.updateMessage}"/></p>
    
    
    
</aura:component>

 

({
    updateMessage : function(component, event, helper) {
        component.set("v.welcomemessage", "updated :: Child message");
        component.set("v.acc",{'sobjectType':'Account',
                               'Name': 'Updated: Child Account'
                              });
        component.set("v.booleanValue", "false");
        component.set("v.numberValue", "120.90");
        component.set("v.stringValue", "updated by Child stringValue message");
        component.set("v.listValue", "['First', 'Second', 'Third']");
     },
    
    
})

Here is the parent Component which is passing referring the child component to and pass the attributes by using Bound expression

<aura:component >
   
   <b> Parent Compoent :</b>
     
    <aura:attribute name="parentAttr" type="String" default="Welcome to Parent Message"/>
    <aura:attribute name="accParnet" type="Account" default="{'sObjectType':'Account' , 'Name':'Parent Account '} "/>
    <aura:attribute name="booleanValue" type="Boolean"/>
    <aura:attribute name="numberValue" type="Double"/>
    <aura:attribute name="stringValue" type="String"/>
    <aura:attribute name="listValue" type="List" default="['red', 'green', 'blue']"/>
    <aura:attribute name="mapValue" type="Map" default="{ a: 'label1', b: 'label2' }"/>
    
    
    <p>Parent Component Primitive type: {!v.parentAttr}</p>
    <p>Parent Component Non Primitive Types : {!v.accParnet.Name}</p>
   
    <div >{!v.booleanValue}</div>
    <div >{!v.numberValue}</div>
    <div>{!v.stringValue}</div>
    <div>{!v.mapValue}</div>
    <div>
        <aura:iteration aura:id="box" items="{!v.listValue}" var="message" indexVar="index">
            {!index}:{!message}<br />
        </aura:iteration>
    </div>
    <br/>
    
    <div>
        
        <c:ChildExpr1 aura:id="innerCmp" stringValue="{!v.stringValue}" 
                      booleanValue="{!v.booleanValue}" numberValue="{!v.numberValue}" listValue="{!v.listValue}" 
                      mapValue="{!v.mapValue}" welcomemessage="{!v.parentAttr}" acc="{!v.accParnet}"/>
        
        
    </div>
      <p><ui:button label="Update Message - Parent"
                  press="{!c.updateParentMessage}"/></p>
  
    
</aura:component>

 

({
    updateParentMessage: function(cmp) {
        cmp.set("v.parentAttr", "updated parent attribute");
        cmp.set("v.accParnet",{'sobjectType':'Account',
                               'Name': 'Updated: Parent Account'
                              });
        cmp.set("v.booleanValue",false);
        cmp.set("v.numberValue","8335");
        cmp.set("v.stringValue","CHANGED string value");
    },
    
    
})

If you click on Update Message – Parent  Button those changes will be now propagated to the child component and vice versa which is similar to two-way data binding. 

 

Now Replace the child component invocation in the Parent Component with the below code by using Unbound Expression Now the parent component changes will not propagate to the child component which acts like as unidirectional binding. 

   
        <c:ChildExpr1 aura:id="innerCmp" stringValue="{#v.stringValue}" 
                      booleanValue="{#v.booleanValue}" numberValue="{#v.numberValue}" listValue="{#v.listValue}" 
                      mapValue="{#v.mapValue}" welcomemessage="{#v.parentAttr}" acc="{#v.accParnet}"/>

Now When you click Update Child Component data its will update only child component attributes and when you click on the Update Message -Parent parent component its update the parent component data which is unidirectional data binding. Now let see how handler works with unbound and bound expression.When you use a bound expression, a change in the attribute in the parent or child component triggers the change handler in both components. When you use an unbound expression, the change is not propagated between components so the change handler is only triggered in the component that contains the changed attribute.

Now update childExpr1.cmp with below code

<aura:component >
    <aura:attribute name="childAttr" type="String" />
    <aura:handler name="change" value="{!v.childAttr}" action="{!c.onChildAttrChange}"/>  
    <p>childExpr childAttr: {!v.childAttr}</p>
    <p><lightning:button label="Update childAttr"
                         onclick="{!c.updateChildAttr}"/></p>
</aura:component>

Here is the controller

({
    updateChildAttr: function(cmp) {
        cmp.set("v.childAttr", "updated child attribute");
    },
    onChildAttrChange: function(cmp, evt) {
        console.log("childAttr has changed");
        console.log("old value: " + evt.getParam("oldValue"));
        console.log("current value: " + evt.getParam("value"));
    }
})

Here is the ParentExpr1.cmp

<aura:component >
    <aura:attribute name="parentAttr" type="String" default="parent attribute"/>
    <aura:handler name="change" value="{!v.parentAttr}" action="{!c.onParentAttrChange}"/>
    <c:childExpr1 childAttr="{!v.parentAttr}" />
    <p>parentExpr parentAttr: {!v.parentAttr}</p>
    <p><lightning:button label="Update parentAttr"
                         onclick="{!c.updateParentAttr}"/></p>
</aura:component>
({
    updateParentAttr: function(cmp) {
        cmp.set("v.parentAttr", "updated parent attribute");
    },
    onParentAttrChange: function(cmp, evt) {
        console.log("parentAttr has changed");
        console.log("old value: " + evt.getParam("oldValue"));
        console.log("current value: " + evt.getParam("value"));
    }
})

Press the Update parentAttr button. The change handlers for c:parentExpr1 and c:childExpr1 are both triggered as we’re using a bound expression.

Now Change c:parentExpr1 to use an unbound expression instead as like this. <c:childExpr1 childAttr=”{#v.parentAttr}” />  which use an unbound expression, the change is not propagated between childExp1.cmp and parentExpr1.cmp .</c:

 

 

 

Lightning Aura.Action Attributes

In this blog, I am going to explain salesforce lightning Aura.Action Attribute Type.With the Aura.Action attribute type you can able to pass the actions handlers from the parent component to child components such as on-click or other HTML actions like on** actions.  Although Aura.Action works for passing an action handler to a child component, its recommended for registering an event in the child component and firing the event in the child‚Äôs controller instead. Then, handle the event in the parent component. This example demonstrates how to pass an action handler from a parent component to a child component.Here‚Äôs the child component with the Aura.Action attribute. The on-click handler for the button uses the value of the on-click attribute, which has the type of Aura.Action.Create the new Lightning component with below code.
AuraAction.cmp

<aura:component>
    <aura:attribute name="pressButton" type="Aura.Action" required="true"/>
    <aura:attribute name="pressDiv" type="Aura.Action" required="true"/>
    
    <ui:button aura:id="theButton" label="Press Me" press="{!v.pressButton}"/>
    <div aura:id="theDiv" onclick="{!v.pressDiv}">Click Me</div> 
</aura:component>

The above component is having two Aura.Action attributes which are used to pass from the parent component to child component on invoke on button press and click on div section handler actions.

AuraActionInvoke.cmp

The below component  is parent component which passes the action to the child component

<aura:component>
    <aura:attribute name="push" type="Boolean" default="false"/>
    <div aura:id="displayResult">No action has run yet</div>
    <c:AuraAction aura:id="fixture" pressButton="{!c.pressButton}"  pressDiv="{!c.pressDiv}"/>
    
</aura:component>
({
    pressDiv: function(cmp, event) {
        var div = cmp.find("displayResult");
        if (div) {
            div.getElement().innerHTML = "Div Action is Presed";
        }
    },
    pressButton: function(cmp, event) {
        var div = cmp.find("displayResult");
        if (div) {
            div.getElement().innerHTML = "Button Action is Pressed";
        }
    },
    
})

Simple Auraapp.app

<aura:application >
    <c:AuraActionInvoke/>	
</aura:application>

Now if you see the above app, when the user clicks on the Press Me button it will pass the action handler from the parent component to child component. Similarly, even user click on Click Me text also passes the action handler to child component and update the parent component.

 

Lightning Aura method

In this blog, I am going to explain how to use the aura: method which allows you to directly call a method in a component‚Äôs client-side controller instead of firing and handling a component event.Here is the simple component “AuraMethod” which contains method “defaultParamers”  with the action called loadDefaultParams

<aura:component>
    <aura:handler name ="init" value="{!this}" action="{!c.doInit}"/>
    <aura:method name="defaultParamers" action="{!c.loadDefaultParams}">
        <aura:attribute type="String" name="header" default="Salesforce Header" />
        <aura:attribute type="String" name="footer" default="Salesforce Footer" />
        <aura:attribute type="String" name="title" default="Salesforce" />
    </aura:method>
    
</aura:component>

In the component controller doInit method I am calling the component  method with the name as shown below

        component.defaultParamers();

which hooks the loadDefaulParams method action to retrieve the values from the component action handler.

({
    doInit : function(component, event, helper) {
        component.defaultParamers();
    },
    loadDefaulParams : function(component, event, helper) {
        var params = event.getParam('arguments');
        console.log(params);
        if (params) {
            var title = params.title;
            var header = params.header;
            var footer = params.footer;
        }
    }
})

Calling Server Side Action

Now let’s consider the defaultParamers aura:method calls a server-side controller action to pass the method parameters. now server-side controller will return the result asynchronously so to handler the response we invoke the callback passed into the aura: method and set the result as a parameter in the callback.

 Define the apex class as shown below
public class AuraMethodController {
    @AuraEnabled
    public static List<String> getServerSideParams(){
        return new List<String>{'Salesforce header from Server' ,'Salesforce footer from Server' , 'Salesforce title from Server' };
    }    

}

Modify the component as shown below.

<aura:component controller="AuraMethodController">
    <aura:handler name ="init" value="{!this}" action="{!c.doInit}"/>
    <aura:method name="defaultParamers" action="{!c.loadDefaultParams}">
        <aura:attribute type="String" name="header" default="Salesforce Header" />
        <aura:attribute type="String" name="footer" default="Salesforce Footer" />
        <aura:attribute type="String" name="title" default="Salesforce" />
    </aura:method>
    
</aura:component>

Now in the controller, we have defined the “onSucess” callback function to handle the server side controller response. But in the below controller I am simply printing the server side response on callback function to console.

({
    doInit : function(component, event, helper) {
        component.defaultParamers();
    },
    loadDefaultParams : function(component, event, helper) {
        var params = event.getParam('arguments');
        var onSucess = function(result){
            console.log(result);
        }
        if (params) {
            onSucess;
        }
        var action = component.get("c.getServerSideParams");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                onSucess(response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    
})

Parent component to call a method on a child component

 aura: method is used to communicate down the containment hierarchy means from the parent component to child components.To communicate up the containment hierarchy, fire a component event in the child component and handle it in the parent component.Here are the child components

AuraMethod.cmp

<aura:component >
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:method name="defaultParamers" action="{!c.loadDefaultParams}">
        <aura:attribute type="String" name="header" default="Salesforce Header" />
        <aura:attribute type="String" name="footer" default="Salesforce Footer" />
        <aura:attribute type="String" name="title" default="Salesforce" />
    </aura:method>
    
</aura:component>
({
    doInit : function(component, event, helper) {
        component.defaultParamers();
    },
    loadDefaultParams : function(component, event, helper) {
        var params = event.getParam('arguments');
        if (params) {
            var title = params.title;
            var header = params.header;
            var footer = params.footer;
            console.log('title'+title)
        }
    },
    
})

Here is the below parent component which is used to pass the parent component data to the child component of the button click.

AuraMethodInvoke.cmp

<aura:component >
    <c:AuraMethod aura:id="child" />
    <aura:attribute name="header" type="String" default="Parent header"/>
    <aura:attribute name="title" type="String" default="Parent title"/>
    <aura:attribute name="footer" type="String" default="Parent footer"/>
    <lightning:button label="parent component to call a method on a child component"
                      onclick="{! c.callAuraMethod}" />
      
</aura:component>

 

({    
    callAuraMethod : function(component, event, helper) {
        var childCmp = component.find("child");
       var auraMethodResult = childCmp.defaultParamers(component.get('v.header') ,                                                       component.get('v.footer') ,                                                       component.get('v.title'));
     },
})

AuraMethodTest.app

<aura:application >
    <c:AuraMethodInvoke />
</aura:application>

when the user clicks on the parent component button which will get the data from the parent component attributes and pass it to the child component.

Method with Interface

Define the simple interface with the aura method as shown below.

AuraMethodIntf.intf

<aura:interface description="Interface template">
    
    <aura:method name="defaultParamers" action="{!c.loadDefaultParams}">
        <aura:attribute type="String" name="header" default="Salesforce Header" />
        <aura:attribute type="String" name="footer" default="Salesforce Footer" />
        <aura:attribute type="String" name="title" default="Salesforce" />
    </aura:method>
    
    
    
</aura:interface>

And then you can implement the interface as shown below.

<aura:component implements="c:AuraMethodIntf">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
</aura:component>
({
    doInit : function(component, event, helper) {
        component.defaultParamers();
    },
    loadDefaultParams : function(component, event, helper) {
        var params = event.getParam('arguments');
        if (params) {
            var title = params.title;
            var header = params.header;
            var footer = params.footer;
            console.log('title'+title);
            console.log('header'+header);
            
            console.log('footer'+footer);
            
        }
    },
    
})

 

 

 

 

Lightning Component Facets

In this blog post, I am going to explain salesforce lightning facets. lighting facets are nothing but attributes of type Aura.Component[] with the array of attributes like body, title etc.To define your own facet, add an aura:attribute tag of type Aura.Component[] to your component. The body attribute has type Aura.Component[] .Now to start with I created a new lighting component with name AuraFacet.cmp with below code.

<aura:component >
    <aura:attribute name="title" type="Aura.component[]" />
    <aura:attribute name="footer" type="Aura.component[]"/>
    <section>
        <div><span></span>{!v.title}</div>
        <div><span> </span>{!v.body}</div>
        <div><span></span>{!v.footer}</div>
    </section>
    
</aura:component>

This is the component which will have two attribute types title and footer facets that are passed from the invoked component.Now I created a component name facetwrapper.cmp with the below code.

<aura:component controller="FacetController">
    <aura:handler name="init" value="this" action="{!c.doInit}"/>
    <aura:attribute name="toggle" type="Boolean" default="true"/>
    <aura:attribute name="org" type="Organization" default=""/>
    
    <section>
        <aura:if isTrue="{!v.toggle}">
            <div>
                <div>
                    <c:AuraFacet aura:id="f1">
                        <aura:set attribute="title">
                            <ui:outputText value="Salesforce Lightning Component Title "/>
                        </aura:set>
                       
                         <aura:set attribute="body">
                            <ui:outputText value="Salesforce Lightning Component Body"/>
                        </aura:set>
                       
                        
                        <aura:set attribute="footer">
                            <p> Copyright 2017 @{!v.org.Name}  - {!v.org.Street} , {!v.org.City} ,{!v.org.State} ,{!v.org.Country} </p>
                             
                        </aura:set>
                        
                    </c:AuraFacet>
                </div>
                
            </div>
        </aura:if>
        <ui:button label="ToggleIf" press="{!c.toggle}" />
    </section>
</aura:component>

 

({
    doInit: function (cmp) {
        var action = cmp.get("c.getOrgDetails");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var resp = response.getReturnValue();
                cmp.set("v.org", resp);
            }
        });
        $A.enqueueAction(action);
        
        
    },
    toggle: function (cmp) {
        cmp.set('v.toggle', !cmp.get('v.toggle'));
    },
  
})

 

public class FacetController {
    @AuraEnabled
    public static Organization getOrgDetails(){
        return [Select Id , Name, Street , City , Country , PostalCode  from Organization] ; 
        
    } 
}

Now if you see the value of an attribute are passed by using the <aura:set> tag.Set tag is used to set the footer and body and title attributes from the wrapper component as shown below.

 

Lightning Application Events

Introduction

In this blog post, I am going to explain how to use the application events.Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All
components that provide a handler for the event are notified.But its good practice to use the component events whenever possible instead of application events.Create an application event contains there steps

Step 1: Create an Application event
Create a new application event with below code as shown below. appEvent.evt

<aura:event type="APPLICATION">
    <aura:attribute name="message" type="String"/>
</aura:event>

Step 2: Register an Event

A component registers that it may fire an application event by using <aura:registerEvent> in its markup. The name attribute is required but not used for application events. The name attribute is only relevant for component events. This example uses name=”</aura:appEvent” but the value isn‚Äôt used anywhere.

<aura:registerEvent name="appEvent" type="c:appEvent"/>

Step 3 : Fire an Event
Use $A.get(“e.myNamespace:myAppEvent”) in JavaScript to get an instance of the myAppEvent event in the myNamespace namespace.

var appEvent = $A.get("e.c:appEvent");
appEvent.setParams({ "myParam" : myValue });
appEvent.fire();

Put All together

Now lets put all together to understand the application events.Here below is the component which will trigger the application events.

AppNotifier.cmp

<aura:component>
    <b>  Notifer Component</b>
    <p> Please Enter the text and then Click here to fire button </p>
    <ui:inputText aura:id="inpId"  value="This is Really cool ..!" required="true"/>
    
    <aura:registerEvent name="appEvent" type="c:appEvent"/>
    <p><lightning:button
                         label="Click here to fire an application event"
                         onclick="{!c.fireApplicationEvent}" />
    </p>
</aura:component>

 

({
    fireApplicationEvent : function(cmp, event) {
        var appEvent = $A.get("e.c:appEvent");
        var inpText = cmp.find("inpId").get("v.value");
        appEvent.setParams({
            "message" :inpText  });
        appEvent.fire();
    }
})
.THIS{
    color: #2f5687;
    font-size:20px;
}

AppHandler.cmp

AppHandler is component that will handle the event notification which is fired from the AppNotifer component and handle them

<aura:component >
    <hr/>
    <b>  Handler Component</b>
    <aura:attribute name="messageFromEvent" type="String"/>
    <aura:handler event="c:appEvent" action="{!c.handleApplicationEvent}"/>
    <p>{!v.messageFromEvent}</p>
</aura:component>
({
    handleApplicationEvent : function(cmp, event) {
        var message = event.getParam("message");
        cmp.set("v.messageFromEvent", message);
            },
})
.THIS{
    color: #FF5733;
    font-size:20px;
}

AppContainer.cmp

<aura:component >
    <c:AppNotifier/>
    <c:AppHandler/>
    
</aura:component>