Shared Helper Code in Lightning Components

I feel like I am duplicating a lot of javascript code while creating helpers for different but related components. Is there a way to have like a shared helper, or maybe a global helper. What other techniques are there to share javascript code between components?

Answer

EDIT 3 – Even better you can now return a value from your called method! This means that the technique below is useful for ASYNC calls, but in many instances, you can skip the callback and just get the result directly into a var

EDIT 2 – Salesforce supports this – see bottom.

EDIT Added Example

I can think of one way you could achieve this.

You would create a component that you would include in your markup. This component would expose a <aura:method> that would perform your work.

Your could pass in parameters to the method like you would in any method.

For return values, you could define a callback as an attribute that would call a function defined on the parent, or you could use a component event to broadcast the result back to the parent

I have an example of how to implement the callback in an answer here

Here is how I would implement this. First define the utility component:

<aura:component >
    <aura:method name="sayHello" action="{!c.greet}" > 
        <aura:attribute name="personName" type="String" default="Doug" />
        <aura:attribute name="callBack" type="function" default="" />
    </aura:method>
</aura:component>

With the method greet being:

({
    greet : function(component, event, helper) {
        var params = event.getParam('arguments');
        if (params) {
            var personName = params.personName;
            var callBack = params.callBack;
            callBack('hello ' + personName);
        }
    }
})

Then to call the helper (and get a response) from the parent, you would do this:

<aura:application >
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <c:UtilityMethods aura:id="utilityMethods"/>
</aura:application>

And call the method on the utility object here, passing in the callback:

({
    init : function(component, event, helper) {
        var utility = component.find("utilityMethods");
        utility.sayHello("Caspar", function(result){
            alert(result);
        });
    }
})

This works well – and it’s supported – see image here:

enter image description here

Note the attribute type – function. I’ve changed my example above to reflect this. Reference on the Salesforce Developer Relations Blog.

Attribution
Source : Link , Question Author : Chris Mullins , Answer Author : Caspar Harmer

Leave a Comment