Skip to content

listenOn() ​

ts
function listenOn(
   to: ListenTarget, 
   name: string, 
   options?: AddEventListenerOptions
): MethodDecorator;

Decorator factory for listeners on targets the typed decorators do not cover: a custom event on window, a media query list, an element found at runtime.

Pass a function for targets that only exist in a browser, like window or document: it is called when the element connects, so a module using the decorator can still be imported where there is no such global, e.g. while server-side rendering. A target passed as is has to exist when the class is defined.

Parameters ​

to ​

ListenTarget

the target to listen on, or a function receiving the element

name ​

string

the event name

options? ​

AddEventListenerOptions

optional event listener options

Returns ​

MethodDecorator

Example ​

ts
const listenColorSchemeChange = () => listenOn(() => window, 'app-color-scheme:change');

class MyComponent extends LitElement {
  ⁠@listenColorSchemeChange()
  protected handleColorSchemeChange(event: CustomEvent<ColorScheme>) {}
}