0

im having a simple web component running on my page. By a button click i simply remove the element expecting that the element and the class behind it is getting killed. But actually it keeps running, for example event listeners are still running even after removing it from the DOM.

This is how i add it to the DOM and make it load:

import { LightningElement, createElement } from 'lwc';
import App from 'my/app';

export default class App extends LightningElement {
  ...
  const appinner = createElement('my-app', { is: App });
  document.body.appendChild(app);
  ...
}

Then i simply remove it by this:

const app = document.querySelector('my-app');
app.remove(); // or app.parentNode.removeChild(app);

Everything in my "App" class is still running even when its gone. How can i really make it unload (or deconstruct) or even kill so no logic keeps running.

Update: Missed to mention i am using LWC library from lwc.dev. And the proper way of injecting an element is described here: Link

Update2: Added more code to show how its really done using the LWC.dev library

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
NovumCoder
  • 4,349
  • 9
  • 43
  • 58
  • From what's said here, you cannot pass directly a class Name in the "is" option, you have to define a customElement and bind it to a name, which you have to pass in that "is". https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement – Peterrabbit Mar 03 '22 at 19:55
  • But it is working. Im using the library from lwc.dev, this is how you inject the component into a page. – NovumCoder Mar 03 '22 at 19:57
  • Oh ok so the createElement function is not the one defined on `document`. Logically your javascript object should stop existing when all references to it are out of scope. So maybe there a subscription to your object somewhere, like event listeners, timeout, promises or type of asynchronous closure that could remain unresolved. – Peterrabbit Mar 03 '22 at 20:03
  • Use the Lightning Web Components issue list – Danny '365CSI' Engelman Mar 03 '22 at 20:33
  • 2
    Event listeners that are attached outside of the component's DOM tree must be properly removed in `disconnectedCallback`. – connexo Mar 09 '22 at 18:49

0 Answers0