There are basically two ways to do this.
Option 1: Extend a Component
You can extend an extensible component to share helper methods.
BaseCmp
BaseCmp.cmp
<aura:component extensible="true">
</aura:component>
BaseCmpHelper.js
({
helperMethod1: function() {
// do stuff here
}
})
ChildCmp
ChildCmp.cmp
<aura:component extends="c:BaseCmp">
<aura:handler name="init" value="{!this}" action="{!c.init}" />
</aura:component>
ChildCmpController.js
({
init: function(component, event, helper) {
helper.helperMethod1();
}
})
Notes:
You can only extend one component. You can chain extensions together, but not recommended (e.g. Base -> Child1 -> Child2). This will have a performance impact.
Methods in child components with the same name as in the parent components will override the parent definition. Make sure all names are unique.
Option 2: Call a Controller Method
You can use aura:method
to call a controller method.
utils
utils.cmp
<aura:component>
<aura:method name="util1" action="{!c.callUtilMethod}" description="Calls util1">
<aura:attribute name="aParam" type="String" />
</aura:method>
</aura:component>
utilsController.js
({
callUtilMethod: function(c,e,h) {
return h.utilMethod1(c, e.getParam("arguments"));
}
})
utilsHelper.js
({
utilMethod1: function(c,args) {
// do what you want here, then return...
return someValue;
}
})
This is called through an instance of the component.
main
main.cmp
<aura:component>
<c:utils aura:id="utils" />
<!-- ... -->
</aura:component>
mainController.js
({
someMethod: function(c,e,h) {
var retVal = c.find("utils").util({ aParam: "Hello World" });
}
})
You can also do asynchronous return values; define the method's parameter as a Function:
<aura:method name="util1" action="{!c.callUtilMethod}" description="Calls util1">
<aura:attribute name="callback" type="Function" />
</aura:method>
Which you then call normally in your method:
({
utilMethod1: function(c,args) {
// do what you want here, then return...
args.callback(returnValue);
}
})
And would be called with a helper function:
({
someMethod: function(c,e,h) {
var retVal = c.find("utils").util({ callback: h.handleResponse.bind(h, c) }});
}
})
Your response handler then looks like:
({
handleResponse: function(c, retVal) {
// Handle the response here
}
})
Notes:
You can only call methods from components in your own namespace, or global methods from another namespace.
You need an instance of the component to call the helper. You cannot call it without first loading the component. This has implications on performance, so it should be used sparingly, and only as necessary.
There are better ways to share code, such as ltng:require
. These two methods do work, but are not recommended. You can read more about all of this stuff in the documentation.