[SalesForce] Lightning APPLICATION Event Handler (Firing to Old Components)

I've created an APPLICATION Event like below, and try to Fire an event from a component and handling the same in another component. Say I create 2 or 3 Lightning Pages (using Lightning App Builder), the SubComponent Fires an Event which is handled by the MainComponent from the 1st Lightning Page. But when you go to the Second page, the Even is being handled by two Lightning Pages as well (notice the console statements in the chrome console), … similarly if you keep shifting from 1st & 2nd Page .. the console keeps on increase … only one Fire event but multiple Handles… should the Component be Destroyed once unloaded?? Why are they still responding to the event fires which they dont belong?

or Am I doing something wrong, please suggest. Thanks.

<aura:event type="APPLICATION" description="DEMO EVENT">
    <aura:attribute name="data" type="String" required="true"/>
</aura:event>

Main Component (Event Handler):

<aura:component implements="force:appHostable,forceCommunity:availableForAllPageTypes,flexipage:availableForAllPageTypes,force:hasRecordId" access="global">

    <aura:handler event="c:DemoEvent" action="{!c.changeEvent}"/>

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

    <aura:attribute name="data" type="String" description="data" />


    <h1>Cmp: {!v. data }</h1>

</aura:component>

//Main Component Controller

({
    doInit : function(component, event, helper) {
        console.log('doInit')
    },
    changeEvent : function(component, event, helper) {
        console.log('changeEvent: ', event.getParam('data'), new Date().getTime());
        component.set('v.data', event.getParam('data'));
    }
})

Sub Component (Event Fire)

<aura:component implements="force:appHostable,forceCommunity:availableForAllPageTypes,flexipage:availableForAllPageTypes,force:hasRecordId" access="global">
    <aura:attribute name="Lang" type="Map"/>

    <aura:registerEvent name="demoEvent" type="c:DemoEvent"/>

    <h2>SubComponent</h2>
    <button onclick="{!c.sendData}">Send Data</button>
</aura:component>

//Sub Component Controller

({
    doInit : function(component, event, helper) {
        console.log('doInit')
    },
    sendData: function(component, event, helper) {
        console.log('sending data.. 2', new Date().getTime());
        $A.get("e.c:DemoEvent").setParams({
            data: 'from Sub Component: ' + new Date()
        }).fire();
    }
})

Best Answer

i was able to solve this issue today

issue - The old components instances listening to the event fire.

Solution - While we move away from a particular component we need to destroy that components as Salesforce stacks the instances.

In the RENDERER file put the below code

({
    unrender: function(component){
        this.superUnrender();
        component.destroy();
    }
})
Related Topic