Refs & Event Listeners
Safely bind DOM events with automatic cleanup using the lifecycle signal.
The signal Parameter
When a component is removed from the DOM (e.g., during SPA navigation or conditional rendering), any event listeners attached to the document or window can cause memory leaks if they are not removed.
Coralite solves this by providing a standard AbortSignal in the client() context. You must pass this signal to every addEventListener call.
<template id="counter">
<button ref="incrementBtn">Increment</button>
<span>{{ count }}</span>
</template>
<script type="module">
export function server () {
return { count: 0 }
}
export async function client ({ state, refs, signal }) {
const btn = refs('incrementBtn')
// Pass { signal } as the third argument
btn.addEventListener('click', () => {
state.count++
}, { signal })
}
</script>
No Inline Handlers
Coralite strictly forbids inline event handlers in templates (like onclick="..."). This is not just a stylistic choice—it is a hard requirement for Content Security Policy (CSP) compliance.
Attributes like onclick="doThing()" or onsubmit="..." are forbidden in <template>. All event wiring must be done inside the client() block using refs().
How the Signal Works
The signal is automatically aborted when the component disconnects from the DOM. The browser's native event listener API handles the cleanup for you.
// When the component disconnects:
// 1. The signal is aborted.
// 2. The listener is automatically removed.
// 3. No memory leaks.
// You don't need to write:
// return () => btn.removeEventListener('click', fn)