on()
The on() function creates event listeners with automatic cleanup and batched signal updates.
Loading sandbox...
Syntax
Section titled “Syntax”on(eventName, handler)on(eventName, handler, options)Parameters
Section titled “Parameters”eventName
: The event type ('click', 'input', 'keydown', etc.).
handler
: The event handler function.
options (optional)
: Standard addEventListener options (capture, once, passive).
Return value
Section titled “Return value”A callback for use with .ref().
Description
Section titled “Description”For simple event handlers, use props:
el('button').props({ onclick: () => doSomething()})('Click')on() provides additional benefits:
- Automatic cleanup when the element is removed
- Batched updates — multiple signal writes trigger one render
- Multiple listeners on the same element
Usage with ref
Section titled “Usage with ref”el('button').ref( on('click', () => count(count() + 1)))('Click')Multiple listeners
Section titled “Multiple listeners”Stack multiple on() calls:
el('input').ref( on('focus', () => console.log('focused')), on('blur', () => console.log('blurred')), on('input', (e) => value(e.target.value)))()Automatic batching
Section titled “Automatic batching”When a handler updates multiple signals, they’re batched into a single render:
el('button').ref( on('click', () => { // All three updates batched into one render firstName(''); lastName(''); loading(true); }))('Reset')Examples
Section titled “Examples”Basic click
Section titled “Basic click”const count = signal(0);
el('button').ref( on('click', () => count(count() + 1)))('Increment')Input handling
Section titled “Input handling”const text = signal('');
el('input') .props({ type: 'text', value: text, }) .ref( on('input', (e) => text(e.target.value)) )()Form submission
Section titled “Form submission”const query = signal('');
const handleSubmit = () => { console.log('Searching:', query());};
el('input') .props({ type: 'text', placeholder: 'Search...', value: query, }) .ref( on('input', (e) => query(e.target.value)), on('keydown', (e) => { if (e.key === 'Enter') handleSubmit(); }) )()Event options
Section titled “Event options”// Capture phaseon('click', handler, { capture: true })
// Fire once onlyon('click', handler, { once: true })
// Passive (for scroll performance)on('scroll', handler, { passive: true })With props events
Section titled “With props events”You can mix on() with props events:
el('button') .props({ onclick: () => console.log('props handler') }) .ref( on('click', () => console.log('on handler')) )('Both fire')Both handlers fire on click.
When to use on()
Section titled “When to use on()”Use on() when you need:
- Multiple listeners on the same event
- Automatic batching of signal updates
- Event options (
capture,once,passive)
For simple handlers, props (onclick, etc.) are sufficient.