Thursday, September 13, 2018

Best way of using lightning helper method and Switch statements

JavaScript Controllers and Helpers play a key role in Lightning Components Framework. One of the first things people new to the framework wonder is: What exactly is the difference between JavaScript Controllers and JavaScript Helpers. 

 To understand it better, here I'm taking simple example to determine what would get from Helper and why we need to delegate logic to the helper from controller. Though this code incorporated with basic logic like add, sub, mul and div. It has lot of take away's in terms of frame work concepts.  Out put looks as below.







Earlier I have provided similar kind of code to demonstrate getters, setters, hide and seek mechanism, and many more with very basic example to keep the things simple. If you want to check it, please hit this link Simple calci for the same. 

================

Step 1: create a component with the name "NoHelpercmp" and  copy the below mark up code in the new component

Mark up: c:NoHelpercmp 

================
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >

    

    <aura:attribute name="num1" type="integer" />

    <aura:attribute name="num2" type="integer" />    

    <aura:attribute name="num3" type="integer" />

    <aura:attribute name="str" type="String" default="None of them selected"/>
    <lightning:card variant="Narrow" title="My Caluclations" >

        <lightning:input name="input1" label="Enter first number" type="number" value="{!v.num1}" aura:id="abc" id="ccc"/>

        <lightning:input name="input2" label="Enter second number" type="number" value="{!v.num2}" aura:id="xyz"/>

        {!v.str}     <ui:outputNumber value="{!v.num3}"/>

        <aura:set attribute="actions">

            <lightning:buttonGroup >

                <lightning:button label="Div" variant="brand" onclick="{!c.Div}" title="Div Method"  />

                <lightning:button label="Add" variant="success" onclick="{!c.Add}" title="Add Method"  />

                <lightning:button label="Sub" variant="brand" onclick="{!c.Sub}"  />

                <lightning:button label="Mul" variant="destructive"  onclick="{!c.Mul}"  class=""/>

            </lightning:buttonGroup>

        </aura:set>
    </lightning:card>

</aura:component>

==============

Step 2: copy the below code and paste it in the NoHelpercmp Controller

=================

({
    Sub : function(component, event, helper) {

     var n1=parseInt(component.find("abc").get("v.value"));  //repeated code

         var n2=parseInt(component.find("xyz").get("v.value"));  //repeated code

         var c=n1-n2; 

         component.set("v.str","sub of 2 number");

          component.set("v.num3",c);

},

    Mul : function(component, event, helper) {

         var n1=parseInt(component.find("abc").get("v.value"));  //repeated code
         var n2=parseInt(component.find("xyz").get("v.value"));  //repeated code

         var c=n1*n2; 

          component.set("v.str","Mul of 2 number");

      component.set("v.num3",c);

},
Add : function(component, event, helper) {

     var n1=parseInt(component.find("abc").get("v.value"));  //repeated code

         var n2=parseInt(component.find("xyz").get("v.value"));  //repeated code

         var c=n1+n2; 

         component.set("v.str","sub of 2 number");

          component.set("v.num3",c);

},

    Div : function(component, event, helper) {

         var n1=parseInt(component.find("abc").get("v.value"));  //repeated code

         var n2=parseInt(component.find("xyz").get("v.value"));  //repeated code

         var c=n1%n2; 

          component.set("v.str","Mul of 2 number");

      component.set("v.num3",c);

}

})



============

Test the above component by using below application container, It still works but its not a best practice to handle the logic in the controller. Your Js controller methods were not desinged for re-usability  purpose.

step 3 : create aura:application container and replace following code and preview it.

============

<aura:application extends="force:slds">

    <c:NoHelpercmp/>


</aura:application>

================

Mark up: c:Helpercmp 

Follow the similar kind of steps which you followed from step 1 to step 3 and then additionally use the step 4(helper function) which is mentioned below.

================

<aura:component implements="flexipage:availableForAllPageTypes" access="global" >

    

    <aura:attribute name="num1" type="integer" />

    <aura:attribute name="num2" type="integer" />    

    <aura:attribute name="num3" type="integer" />

    <aura:attribute name="str" type="String" default="None of them selected"/>

    
    <lightning:card variant="Narrow" title="My Caluclations" >

        <lightning:input name="input1" label="Enter first number" type="number" value="{!v.num1}" aura:id="abc" id="ccc"/>


        <lightning:input name="input2" label="Enter second number" type="number" value="{!v.num2}" aura:id="xyz"/>

        {!v.str}     <ui:outputNumber value="{!v.num3}"/>

        <aura:set attribute="actions">

            <lightning:buttonGroup >

                <lightning:button label="Div" variant="brand" onclick="{!c.Allcaluclations}" title="Div Method"  />

                <lightning:button label="Add" variant="success" onclick="{!c.Allcaluclations}" title="Add Method"  />

                <lightning:button label="Sub" variant="brand" onclick="{!c.Allcaluclations}"  />

                <lightning:button label="Mul" variant="destructive"  onclick="{!c.Allcaluclations}"  />

            </lightning:buttonGroup>

        </aura:set>

        

        

    </lightning:card>

</aura:component>



=================

Js controller code with delegates business logic to helper.

=================



({

Allcaluclations : function(component, event, helper) {

      helper.Mymethod(component, event, helper);

}

})


==============

Step 4: Helper to perform all the calculations with in the same function

==============

({

    Mymethod : function(component, event, helper) {

        var buttonlabel=event.getSource().get('v.label');

        this.Myswtich(component, event, helper,buttonlabel);


    },


     Myswtich : function(component, event, helper,buttonlabel) {

            var a=parseInt(component.get('v.num1'));

        var b=parseInt(component.get('v.num2'));

        switch (buttonlabel) {

            case 'Add':

                component.set("v.str","Addition of two numbers");       

                var c=a+b; 

                break;

            case 'Sub':

                component.set("v.str","Sub of two numbers");

                var c=a-b; 

                break;

            case 'Mul':

                component.set("v.str","Mul of two numbers");

                var c=a*b; 

                break; 

            case 'Div':

                component.set("v.str","Div of two numbers");

                var c=a%b; 

                break; 

        }

        
        component.set("v.num3",c);


     }

    

})



============

Test the above component by using below application container.

============



<aura:application extends="force:slds">

    
    <c:Helpercmp/>



</aura:application>