onDisconnected

Runs a function when the element is removed.

onDisconnected(fn: () => void): void
onDisconnected(() => {
  socket.close();
});

Parameters

Parameter Type Meaning
fn () => void Runs once when the element is removed

Order on removal

REALM waits one microtask after disconnectedCallback. If the element is connected again by then (it was moved), nothing happens. Otherwise:

  1. onDisconnected hooks run in the order they were registered.
  2. signal aborts: listeners, requests, timers and debounced calls stop.
  3. Observers stop, cleanups returned from onConnected and observe run, prop accessors and defineMethods are removed.
  4. The shadow root is emptied.

Adding the element again later creates a fresh instance: the script runs again.

Example

Previewindex.htmlgoodbye-note.htmlgoodbye-host.html

I will log when I am removed.

Toggle the note Not removed yet.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>onDisconnected demo</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@realmorg/realm@alpha/dist/realm.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@realmorg/ui@alpha/dist/theme.css">
  <script type="module" src="https://cdn.jsdelivr.net/npm/@realmorg/realm@alpha/dist/realm.js"></script>
</head>
<body>
  <import-element from="https://cdn.jsdelivr.net/npm/@realmorg/ui@alpha/components/button.html"></import-element>

  <import-element from="./goodbye-note.html"></import-element>
  <import-element from="./goodbye-host.html"></import-element>

  <goodbye-host></goodbye-host>
  <output id="goodbye-log">Not removed yet.</output>
</body>
</html>
<custom-element name="goodbye-note">
  <script>
    onDisconnected(() => {
      document.getElementById("goodbye-log").value = `Removed at ${new Date().toLocaleTimeString()}`;
    });
  </script>

  <p>I will log when I am removed.</p>
</custom-element>
<custom-element name="goodbye-host">
  <script>
    const view = useState({ shown: true });
  </script>

  <is-visible when="#view.shown"><goodbye-note></goodbye-note></is-visible>
  <ui-button variant="outline" onclick="view.shown = !view.shown">Toggle the note</ui-button>
</custom-element>

Edit this page on GitHub · View as Markdown