useOn() / useOnDocument() / useOnWindow() - Programmatic Listeners
There are times when your app needs to add a conditional listener. Sometimes a listener name is unknown, or you need to use an imperative approach to set up a listener.
Qwik provides the following functions to attach a listener:
Function | Description |
---|---|
useOn() | Listen to events on the current component's root element. |
useOnDocument() | Listen to events on the document object. |
useOnWindow() | Listen to events on the window object. |
Your task: Set up a click listener on the component to call
alert('Hello world!')
.
$
Understanding the The $
function signals Qwik to lazy load a reference. When setting up a listener with useOn
, the second argument is a Qwik URL.
Qwik URLs (QRL) are lazy-loadable references to your code. If useOn
took a function directly rather than QRL, it would have to eagerly execute to allocate the listener closure. By using a QRL via the $
function, Qwik can lazy load the closure only as click
listener is triggered.