Skip to content

on()

The on() function creates event listeners with automatic cleanup and batched signal updates.

Loading sandbox...
on(eventName, handler)
on(eventName, handler, options)

eventName : The event type ('click', 'input', 'keydown', etc.).

handler : The event handler function.

options (optional) : Standard addEventListener options (capture, once, passive).

A callback for use with .ref().

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
el('button').ref(
on('click', () => count(count() + 1))
)('Click')

Stack multiple on() calls:

el('input').ref(
on('focus', () => console.log('focused')),
on('blur', () => console.log('blurred')),
on('input', (e) => value(e.target.value))
)()

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')
const count = signal(0);
el('button').ref(
on('click', () => count(count() + 1))
)('Increment')
const text = signal('');
el('input')
.props({
type: 'text',
value: text,
})
.ref(
on('input', (e) => text(e.target.value))
)()
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();
})
)()
// Capture phase
on('click', handler, { capture: true })
// Fire once only
on('click', handler, { once: true })
// Passive (for scroll performance)
on('scroll', handler, { passive: true })

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.

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.

  • el() — Element creation with props events
  • batch() — Manual batching alternative