Salesforce Lightning - How To Fire Component Event
Component Events can be fired from the same component. It is used to communicate data to another component. Component events are divided into two sections <aura:registerEvent> ( In this section, we can register the event) and <aura:handler> (In this, we can handle the register event). Usually, one component is interested in the event, as an event aggregator.
We can create a custom component event by using this tag <aura:event> in a .evt resource. In component events, we can take the type attribute value as ‘COMPONENT’ inside the <aura:event> tag.
Example: componentEvent.cmp
To fetch the attribute value from this event, we can call event.getParam("recordByEvent") in the handler’s client-side controller.
Let’s start the discussion about registerEvent and handle
- <aura:registerEvent>: If you want to get a reference to component events in JS. you have to use cmp.getEvent(“EventName”). Where EventName is the name of attribute in <aura:registerEvent>. Let’s take an example for registerEvent:
Fire(): E.g.:
- <aura:handler>: It is the markup of the handler component. E.g.:
Important Point: Name attribute of <aura:handler> is the same as <aura:registerEvent>.
Component Event provides two phases
Bubble phase and Capture phase. In component events, phases are used for the propagation of events. Phases are alike to DOM handling patterns.
Let’s discuss these phases…..
Bubble Phase
Bubble phase is also known as Bubbling. In this, the Event is first captured and handled by the source component and then propagated by application root.
Capture Phase
In this, the Event is first captured by application root and then propagated by source component. The capture phase is also known as trickling, Which recollects the propagation order.
If you want to add a handler for the phase (especially for the capture phase because handlers are connected with bubble phase by default.) Let's see an example for adding a capture phase in the Component event handler:
Salesforce Lightning Component Event
Let’s take an example for the Component Event. In this example, we will see how we can fire events from the child component and handle them in the parent component.
1. Component Event: We can create an event and it is named cmpEvent.evt. It is used to pass data in the event when it’s fired.
2. Notifier Component: (Child component) This component uses <aura:registerEvent>. And the child component is named childCmp.cmp
3. Now we can create the controller for childCmp.cmp.
4. Handler Component: (Parent Component) This component contains the above child component childCmp.cmp. In this we can use the <aura:handler> tag. And the parent component is named ParentComponent.cmp
5. Now we can create the controller for ParentComponent.cmp
Comments
Post a Comment