+ Start a Discussion
Vivek NayakVivek Nayak 

How to define global variable in component helper?

Hi All,
I know local variables cant be accsssed outside function in JS but i have below requirement.

Helper:

({

helper1: func(){
var A=[];
//logic
A.push();
},

helper2: func(){
// I need A here.
cmp.set("v.data",A);
}
}}

As shown above, is there anyway to use variable of one function into another? I have also tried using component event but didnt succeed.
Please guide me.

Thanks,
Ajay K DubediAjay K Dubedi
Hi Vivek, 
1. If you want to use a variable of 1st function into a 2nd function then you can pass it in the argument, when you call the 2nd function in the 1st function.
2. Set your variable at any Attribute of component and then get it in another function.
Try this for 1st:
({

helper1: function(component, event, helper) {
    var A=[];
    //logic
    A.push();
    helper.helper2(component, event, helper, A)
},

helper2:  function(component, event, helper, A) {
    // I need A here.
    component.set("v.data", A);
}
}}
Try this for 2nd:
helper1: function(component, event, helper) {
        var A=[];
        //logic
        A.push();
        component.set("v.data",  A);
},

helper2:  function(component, event, helper, A) {
        // I need A here.
    var A2 = component.get("c.data");
    system.debug(A2);
}
}}
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks,
Ajay Dubedi
Deepali KulshresthaDeepali Kulshrestha
Hi Vivek,

Unlike JavaScript, we have to create aura:attribute in component; which can be used for storing data available to client 

side controller and helper globally.

Basic example

<aura:component>

   
 // attribute
  
  <aura:attribute name="recordId" type="String"/>

  
  // other code

</aura:component>

With this recordId attribute is registered for the component and can be accessed by v.recordId property in client side 

helper and controller.

// getter
component.get("v.recordId");
//
 setter
component.set("v.recordId", "record id value");

One can use a function in helper or controller which returns value but using aura:attribute is much cleaner.

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.



Thanks and Regards,


Deepali Kulshrestha
Vivek NayakVivek Nayak
Hi Deepali,
Thanks for reply. I am already using attributes but problem is once we assign a value to it e cant use old one so i was looking a way to use a variable in helper which is defined once and can be use in any function inseted of using multiple attributes. Anyway its not possible due to local scope so am using attribues only.
Vivek NayakVivek Nayak
Hi Ajay,
First option will return a full function which i dont need. i need a varibale of  first function in to another. I m using second option.

Thanks
Vivek NayakVivek Nayak
Hi All,
Closing this discussion.