Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.
Invoking Actions on Component Initialization
Let’s look at an example.
1<!--initCmp.cmp-->
2<aura:component>
3 <aura:attribute name="setMeOnInit" type="String" default="default value" />
4 <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
5
6 <p>This value is set in the controller after the component initializes and before rendering.</p>
7 <p><b>{!v.setMeOnInit}</b></p>
8
9</aura:component>The magic happens in this line.
1<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>This code registers an init event handler for the component. init is a predefined event sent to every component. Setting value="{!this}" marks this as a value event. You should always use this setting for an init event.
After the component is initialized, the doInit action is called in the component’s controller.
1// initCmp.js
2({
3 doInit: function(cmp) {
4 // Set the attribute value.
5 // You could also fire an event here instead.
6 cmp.set("v.setMeOnInit", "controller init magic!");
7 }
8})The doInit action sets an attribute value, but it could do something more interesting, such as firing an event.
If a component is contained in another component or app, the inner component is initialized first.