Overview

onConnect(cb) fires after the decorated element is connected to the live DOM. onDisconnect(cb) fires when it is removed. Both receive the element as the first argument.

These are element-scoped — useful when a specific node (not the whole component) needs focus, measurement, or third-party teardown.

Element directives vs component hooks

API
Scope
Notes
onConnect / onDisconnect Per element Element directives on a single node in the template.
onMount / onCleanup Per component Outer-function hooks for the whole component lifetime. See /docs/lifecycle/on-mount.
eleHook Full imperative Mount + onUpdate + onCleanup when you need ongoing sync.

Element connect / disconnect log

onConnect fires after the element is appended to the live DOM tree; onDisconnect fires just before it is removed. Both receive the element itself as the first argument.

import { html, atom, onConnect, onDisconnect, nothing, renderApp } from 'mates';

const App = () => {
const show = atom(true);
const log = atom([]);
const addLog = (msg) => log.set(prev => [msg, ...prev].slice(0, 6));

return () => html`
<div class="m-col m-gap">
<button @click=${() => show.set(v => !v)}>
${show() ? 'Remove' : 'Add'} element
</button>
${show() ? html`
<div
class="card card-body"
${onConnect(el => addLog('✓ Element connected to DOM'))}
${onDisconnect(el => addLog('✗ Element removed from DOM'))}
>
This element fires onConnect / onDisconnect
</div>
` : nothing}
<div class="card card-body">
<span class="overline">Lifecycle log</span>
${log().length === 0
? html`<div class="mono subtle">Toggle the element…</div>`
: log().map(e => html`<div class="mono">${e}</div>`)
}
</div>
</div>
`;
};
renderApp(App, document.getElementById('app'));

Autofocus input

onConnect receives the element — focus an input when it mounts.

import { html, atom, onConnect, nothing, renderApp } from 'mates';

const App = () => {
const show = atom(true);
return () => html`
<div class="m-col m-gap">
<button @click=${() => show.set(v => !v)}>Toggle</button>
${show()
? html`<input ${onConnect(el => el.focus())} placeholder="Auto-focused" />`
: nothing}
</div>
`;
};
renderApp(App, document.getElementById('app'));