Activity Forums Salesforce® Discussions How can we subscribe to an event in Salesforce Lightning Component?

  • shariq

    Member
    September 23, 2018 at 11:06 pm

    To subscribe to an event in lightning component we need to include tag in the containment hierarchy. Subscription of these event depends on the event type i.e. component event or application event. For Component event we write below code.

    In this ‘name’ attribute in should be exactly as name attribute in tag in the component which has fired the component. The ‘action’ attribute of sets the client-side controller action to handle the event. The ‘event’ attribute specifies the event being handled.
    For Handling Application event we write below code

    ‘Event’ and ‘action’ attribute are same as the component event handling, it is just that we do not include ‘name’ attribute to handle the application event.

  • Parul

    Member
    September 24, 2018 at 12:34 am

    In order to use Application event we need to follow the Four simple steps

    1. Create Application Event
    2. Fire the event from the child component
    3. handle the event into Parent Component
    4. Execute the action into Parent Component

    Step 1 – Create Application Event

    Open developer console and then File -> New -> Lightning Event -> name it applicationEvent and use below code.

    <aura:event type=”APPLICATION” description=”Event template” >
    <aura:attribute name=”testWord” type=”String” />
    </aura:event>

    Step 2 – Register the event

    Unlike the Component we do not need to register the Application Event.

    Step 3 – Fire the component Event

    Use below code in javascript to execute the event.

    ({
    handleClick : function(component, event, helper) {
    var appEvent = $A.get(‘e.c:applicationEvent’);
    appEvent.setParams({
    “testWord” : ‘Value From Application Event’
    });
    appEvent.fire();
    },
    })

    Explanation : –

    $A.get(‘e.c:applicationEvent’); – Finds the event with the name provided after c: and in our case it it applicationEvent.
    setParams : – is used to send the parameters to the parent component if we are using any attribute in the event. In our case we have used attribute testWord
    fire() :- Executes the event

    Step 4: – Handle the Event in any Component

    A single line of code to handle the event into the component

    <aura:handler event=”c:applicationEvent” action=”{!c.doHandleCompEvent}” />

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos