Strange behavior when component manually destroyed?

It seems like calling component.destroy() does not actually destroy the component from the lightning cache. I am having to manually destroy my component to avoid duplicated application events as seen here, but it seems like it is not behaving the way I expect it to.

Whichever component is loaded first in the queue will not be recreated when navigating back to it. Here is the example.
https://vid.me/QGCY

TestTabA.cmp

<aura:component  implements="force:appHostable">
  <ltng:require scripts="{!join(',', '/resource/Mynamespace__JQuery' )}" afterScriptsLoaded="{!c.initJS}" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:handler event="aura:locationChange" action="{!c.updateDestroy}"/>
</aura:component>

TestTabAController.js

({
    initJS : function(component, event, helper) {
        if (component.isValid()) {
            console.log("loaded JS for tab A");
        }
    },
    doInit : function(component, event, helper) {
        if (component.isValid()) {
            console.log("called init for tab A");
        }
    },
    updateDestroy : function(cmp, event, helper) {
        cmp.destroy();
    },
})

TestTabB.cmp

<aura:component  implements="force:appHostable">
  <ltng:require scripts="{!join(',', '/resource/Mynamespace__JQuery' )}" afterScriptsLoaded="{!c.initJS}" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:handler event="aura:locationChange" action="{!c.updateDestroy}"/>
</aura:component>

TestTabBController.js

({
    initJS : function(component, event, helper) {
        if (component.isValid()) {
            console.log("loaded JS for tab B");
        }
    },
    doInit : function(component, event, helper) {
        if (component.isValid()) {
            console.log("called init for tab B");
        }
    },
    updateDestroy : function(cmp, event, helper) {
        cmp.destroy();
    },
})

Answer

I found some issues when you try to destroy yourself, but it works much better when your parent destroys you. Try putting a wrapper component, with your component in a DIV section. and when the location is changed, then set the v.body of that div to and empty list of components:

cmp.set("v.body", []);

Attribution
Source : Link , Question Author : Jason Lee , Answer Author : Andres Perez

Leave a Comment