Use <aura:method> to define a method as part of a component's API. This enables you to directly call a method in a component’s client-side controller instead of firing and handling a component event. Using <aura:method> simplifies the code needed for a parent component to call a method on a child component that it contains.
Communicate Between Components
Use aura:method to communicate down the containment hierarchy. For example, a parent component calls an aura:method on a child component that it contains.
To communicate up the containment hierarchy, fire a component event in the child component and handle it in the parent component.
Syntax
Use this syntax to call a method in JavaScript code.
cmp.sampleMethod(arg1, … argN);
cmp is a reference to the component.
sampleMethod is the name of the aura:method.
arg1, … argN is an optional comma-separated list of arguments passed to the method. Each argument corresponds to an aura:attribute defined in the aura:method markup.
Using Inherited Methods
A sub component that extends a super component has access to any methods defined in the super component.
An interface can also include an <aura:method> tag. A component that implements the interface can access the method.
Example
Let's look at an example app.
<!-- c:auraMethodCallerWrapper.app -->
<aura:application >
<c:auraMethodCaller />
</aura:application>
c:auraMethodCallerWrapper.app contains a c:auraMethodCaller component.
<!-- c:auraMethodCaller.cmp -->
<aura:component >
<p>Parent component calls aura:method in child component</p>
<c:auraMethod aura:id="child" />
...
</aura:component>
c:auraMethodCaller is the parent component. c:auraMethodCaller contains the child component, c:auraMethod.
We'll show how c:auraMethodCaller calls an aura:method defined in c:auraMethod.
We'll use c:auraMethodCallerWrapper.app to see how to return results from synchronous and asynchronous code.
-
Return Result for Synchronous Code
aura:methodexecutes synchronously. A synchronous method finishes executing before it returns. Use thereturnstatement to return a value from synchronous JavaScript code. -
Return Result for Asynchronous Code
aura:methodexecutes synchronously. Use thereturnstatement to return a value from synchronous JavaScript code. JavaScript code that calls a server-side action is asynchronous. Asynchronous code can continue to execute after it returns. You can’t use thereturnstatement to return the result of an asynchronous call because theaura:methodreturns before the asynchronous code completes. For asynchronous code, use a callback instead of areturnstatement.
See Also