pub fn use_event_listener<Ev, El, T, F>(
target: El,
event: Ev,
handler: F,
) -> impl Fn() + Clonewhere
Ev: EventDescriptor + 'static,
El: Into<ElementMaybeSignal<T, EventTarget>>,
T: Into<EventTarget> + Clone + 'static,
F: FnMut(<Ev as EventDescriptor>::EventType) + 'static,
Expand description
Use EventListener with ease.
Register using addEventListener on mounted, and removeEventListener automatically on cleanup.
§Usage
use_event_listener(use_document(), visibilitychange, |evt| {
log!("{:?}", evt);
});
You can also pass a NodeRef
as the event target, use_event_listener
will unregister the previous event and register
the new one when you change the target.
let element = create_node_ref();
use_event_listener(element, click, |evt| {
log!("click from element {:?}", event_target::<web_sys::HtmlDivElement>(&evt));
});
let (cond, set_cond) = create_signal(true);
view! {
<Show
when=move || cond.get()
fallback=move || view! { <div node_ref=element>"Condition false"</div> }
>
<div node_ref=element>"Condition true"</div>
</Show>
}
You can also call the returned to unregister the listener.
let cleanup = use_event_listener(document().body(), keydown, |evt: KeyboardEvent| {
log!("{}", &evt.key());
});
cleanup();
§Server-Side Rendering
On the server this amounts to a noop.