[SalesForce] How to get the Lightning Component “destroy” system event to fire

I have a fairly bog standard Lightning Component with markup like:

<aura:component controller="MyController" implements="flexipage:availableForAllPageTypes,force:appHostable,force:hasRecordId,force:hasSObjectName,force:lightningQuickAction" >
    . . . 
    (omitted code)
    . . .
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:handler name="destroy" value="{!this}" action="{!c.handleDestroy}"/>
    <aura:handler event="aura:locationChange" value="{!this}" action="{!c.handleLocationChange}"/>
</aura:component>

and in my controller, actions which look like this:

({

    . . . omitted code . . .

    doInit: function( component, event, helper ) {

        console.log( "doInit" );

    },

    handleDestroy : function( component, event, helper ) {

        console.log( "handleDestroy" );                

    },

    handleLocationChange: function( component, event, helper ) {

        console.log( "location change" );        

    }

})

Both the "init" and "aura:locationChange" events fire and I see the console.log, but the "destroy" event never fires – even when i navigate away e.g. from "Cases" to "Reports" or to a different part of the system entirely.

I need to handle this event for removing event handlers attached to the window. How can I achieve this?

Best Answer

Generally when an component/app runs in LEX, it will not get destroyed as soon as you navigate to a different view. Have a look at the post here. Also destroying component manually has a impact too which explained here.

I believe action associated with destroy event will not be called immediately because of the component destroying issue in LEX.

The right place to remove the event listeners attached to window is in the unrender, which would be called only when the component/app is destroyed.

If unrender does not work properly(i.e due to the component destroying issue), you certainly use the aura:locationChange to remove the event listeners.

Related Topic