fromEvent()

Observable creation operator

Observes events emitted by a Stencil component. Inspired by RxJS’s fromEvent function, this operator allows you to create an observable from DOM events using component instance instead of a DOM element. It also supports event delegation, allowing you to handle events from child elements matching a CSS selector.

See RxJS fromEvent() for more information about the original operator, see JQuery’s on() for more information about event delegation.

fromEvent(cmp, eventName, delegate, options)

Creates an observable emitting events from a Stencil component.

function fromEvent<T extends Event = Event>(cmp: ComponentInterface, eventName: string, delegate?: string, options?: EventHandlerOptions): Observable<T>
function fromEvent<T extends Event = Event>(cmp: ComponentInterface, eventName: string, options?: EventHandlerOptions): Observable<T>
Arguments:
  • cmp (ComponentInterface) – The Stencil component instance for which to observe events.

  • eventName (string) – The name of the event to observe.

  • delegate (string) – An optional CSS selector to delegate the event to.

  • options (EventHandlerOptions) – Optional configuration for the event handler.

Returns:

Observable that emits events of type T.

Return type:

Observable<T>

class EventHandlerOptions()

Configuration options for observing events.

export type EventHandlerOptions = {
    capture?: boolean;
    once?: boolean;
    passive?: boolean;
};
EventHandlerOptions.capture
Type:

boolean

Optional: Yes

Default: false

Indicates that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.

EventHandlerOptions.once
Type:

boolean

Optional: Yes

Default: false

Indicates that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked and observers will be unsubscribed from the observable.

EventHandlerOptions.passive
Type:

boolean

Optional: Yes

Default: false

Indicates that the function specified by listener will never call preventDefault(). If it does, the user agent will ignore it and generate a console warning.

Example

Observe click events on a Stencil component
 1import {
 2    Component,
 3    ComponentInterface,
 4    h,
 5} from '@stencil/core';
 6import { Observable } from 'rxjs';
 7import { fromEvent } from '@runopenode/rxjs-stencil';
 8
 9@Component({
10    tag: 'my-cmp',
11    shadow: true,
12})
13class MyCmp implements ComponentInterface {
14
15    public constructor() {
16         fromEvent<MouseEvent>(this, 'click')
17             .subscribe((event: MouseEvent): void => {
18                 // Handle click event
19             });
20    }
21
22    public render(): any {
23        // Render component template
24    }
25}