Skip to content

@epikodelabs/streamix


@epikodelabs/streamix / fromEvent

Function: fromEvent()

fromEvent<T>(target, event, options?): Stream<T>

Defined in: projects/libraries/streamix/src/lib/streams/fromEvent.ts:41

Creates a stream that emits events of the specified type from the given EventTarget.

This function provides a reactive way to handle DOM events or other events, such as mouse clicks, keyboard presses, or custom events. The stream will emit a new event object each time the event is dispatched.

The stream handles:

  • Promise-based resolution of both target and event name
  • Automatic cleanup when the last subscriber unsubscribes
  • Multicast to multiple subscribers
  • Proper error propagation if event listener setup fails

Type Parameters

T

T extends Event = Event

The type of the event to listen for.

Parameters

target

MaybePromise<EventTarget>

The event target to listen to (e.g., a DOM element, window, or document). Can be a direct EventTarget or a Promise that resolves to one.

event

MaybePromise<string>

The name of the event to listen for (e.g., 'click', 'keydown'). Can be a direct string or a Promise that resolves to one.

options?

Optional event listener options (e.g., { once: false, passive: true }).

boolean | AddEventListenerOptions

Returns

Stream<T>

A stream that emits the event objects as they occur.

Examples

ts
// Basic usage
const clicks = fromEvent(document.getElementById('myButton'), 'click');
clicks.subscribe(console.log);
ts
// With async target (e.g., waiting for DOM element)
const asyncButton = waitForElement('#myButton');
const clicks = fromEvent(asyncButton, 'click');
ts
// With custom event
const customEvents = fromEvent(window, 'my-custom-event');

Released under the GNU AGPL v3 or later.