Skip to main content

createEventListener

Attach typed DOM event listeners that clean up automatically when the Solid owner scope disposes.

View as Markdown

createEventListener and createEventListenerMap attach DOM event listeners to a Window, Document, MediaQueryList, element, or other EventTarget. Each registers its removal with onCleanup in the active Solid owner, so the listener detaches when that scope disposes.

Import#

import { createEventListener, createEventListenerMap } from 'moraine/utils'

Signatures#

function createEventListener<
  TTarget extends EventTarget,
  TType extends EventTypeForTarget<TTarget>,
>(
  target: TTarget | null | undefined,
  type: TType,
  listener: (event: EventMapForTarget<TTarget>[TType]) => void,
  options?: boolean | AddEventListenerOptions,
): void

function createEventListenerMap<TTarget extends EventTarget>(
  target: TTarget | null | undefined,
  listeners: EventListenerMap<TTarget>,
  options?: boolean | AddEventListenerOptions,
): void

EventListenerMap maps event types to either a listener or a [listener, options] tuple. A tuple’s options replace the shared options for that event.

Usage Example#

Single Event with createEventListener#

src/EscapeListener.tsx
import { onMount } from 'solid-js'
import { createEventListener } from 'moraine/utils'

export function EscapeListener(props: { onEscape: () => void }) {
  onMount(() => {
    // Strongly typed: e is KeyboardEvent for window keydown.
    createEventListener(window, 'keydown', (e) => {
      if (e.key === 'Escape') {
        props.onEscape()
      }
    })
  })

  return null
}

Multiple Events with createEventListenerMap#

src/DragObserver.tsx
import { onMount } from 'solid-js'
import { createEventListenerMap } from 'moraine/utils'

export function DragObserver() {
  onMount(() => {
    createEventListenerMap(window, {
      pointermove: (e) => console.log('Pointer at:', e.clientX, e.clientY),
      pointerup: () => console.log('Drag ended'),
      pointercancel: () => console.log('Drag cancelled'),
    })
  })

  return null
}

Features#

  • The event type and event argument narrow from the target: window keydown gives a KeyboardEvent, window resize gives a UIEvent.
  • Cleanup registers through onCleanup in the active owner, including when you call the hook from onMount.
  • A null or undefined target is a no-op; no listener is attached.
  • The hooks are not reactive. They read target, type, and options once. To follow a changing target, call them inside createEffect(on(target, ...)).
  • Call them from a component body, onMount, or an effect. Do not call them inside a ref callback.