onDisconnected
Runs a function when the element is removed.
onDisconnected(fn: () => void): voidonDisconnected(() => {
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:
onDisconnectedhooks run in the order they were registered.signalaborts: listeners, requests, timers and debounced calls stop.- Observers stop, cleanups returned from
onConnectedandobserverun, prop accessors anddefineMethodsare removed. - The shadow root is emptied.
Adding the element again later creates a fresh instance: the script runs again.
Example
I will log when I am removed.
<!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>