Calling Component Methods

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.

Use this syntax to call a method in JavaScript code.

cmp.sampleMethod(arg1, … argN);

cmp is a reference to the component. arg1, … argN is an optional comma-separated list of arguments passed to the method.

Let’s look at an example of a component containing a button. The handler for the button calls a component method instead of firing and handling its own component event.

Here is the component source.

<!--c:auraMethod-->
<aura:component>
    <aura:method name="sampleMethod" action="{!c.doAction}" 
      description="Sample method with parameters"> 
        <aura:attribute name="param1" type="String" default="parameter 1" /> 
    </aura:method>

    <ui:button label="Press Me" press="{!c.handleClick}"/>
</aura:component>

Here is the client-side controller.

/*auraMethodController.js*/
({
    handleClick : function(cmp, event) {
        console.log("in handleClick");
        // call the method declared by <aura:method> in the markup 
        cmp.sampleMethod("1");
    },

    doAction : function(cmp, event) {
        var params = event.getParam('arguments');
        if (params) {
            var param1 = params.param1;
            console.log("param1: " + param1);
            // add your code here
        }
    },
})

This simple example just logs the parameter passed to the method.

The <aura:method> tag set name="sampleMethod" and action="{!c.doAction}" so the method is called by cmp.sampleMethod() and handled by doAction() in the controller.

Note

Note

If you don’t specify an action value, the controller action defaults to the value of the method name. If we omitted action="{!c.doAction}" from the earlier example, the method would be called by cmp.sampleMethod() and handled by sampleMethod() instead of doAction() in the controller.

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.