Function window_event_listener

pub fn window_event_listener<E>(
    event: E,
    cb: impl Fn(<E as EventDescriptor>::EventType) + 'static,
) -> WindowListenerHandle
where E: EventDescriptor + 'static, <E as EventDescriptor>::EventType: JsCast,
Expand description

Creates a window event listener from a typed event, returning a cancelable handle.

use leptos::{
    ev, leptos_dom::helpers::window_event_listener, logging::log,
    prelude::*,
};

#[component]
fn App() -> impl IntoView {
    let handle = window_event_listener(ev::keypress, |ev| {
        // ev is typed as KeyboardEvent automatically,
        // so .code() can be called
        let code = ev.code();
        log!("code = {code:?}");
    });
    on_cleanup(move || handle.remove());
}

§Note about Context

The callback is called outside of the reactive ownership tree. This means that it does not have access to context via use_context. If you want to use context inside the callback, you should either call use_context in the body of the component, and move the value into the callback, or access the current owner inside the component body using Owner::current and reestablish it in the callback with Owner::with.