pub fn use_event_listener<Ev, El, M, F>(
target: El,
event: Ev,
handler: F,
) -> impl Fn() + Clone + Send + Syncwhere
Ev: EventDescriptor + 'static,
El: IntoElementMaybeSignal<EventTarget, M>,
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 = NodeRef::new();
use_event_listener(element, click, |evt| {
log!("click from element {:?}", event_target::<web_sys::HtmlDivElement>(&evt));
});
let (cond, set_cond) = 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();
§SendWrapped Return
The returned closure is a sendwrapped function. It can
only be called from the same thread that called use_event_listener
.
§Server-Side Rendering
On the server this amounts to a noop.