feat: rewrite window_event_listener funtion

This commit is contained in:
luoxiao 2023-05-18 10:55:29 +08:00
parent 284a3be1f7
commit 8efe55780d
2 changed files with 27 additions and 15 deletions

View file

@ -48,12 +48,12 @@ pub fn Slider(
set_mouse_move.set(true);
};
let on_mouse_up = window_event_listener("mouseup", move |_| {
let on_mouse_up = window_event_listener(ev::mouseup, move |_| {
set_mouse_move.set(false);
});
on_cleanup(cx, on_mouse_up);
let on_mouse_move = window_event_listener("mousemove", move |ev| {
let on_mouse_move = window_event_listener(ev::mousemove, move |ev| {
if is_mouse_move.get_untracked() {
if let Some(rail) = rail_ref.get_untracked() {
let ev = ev.unchecked_into::<web_sys::MouseEvent>();

View file

@ -1,16 +1,28 @@
use leptos::window;
use leptos_dom::ev;
use std::borrow::Cow;
use wasm_bindgen::{prelude::Closure, JsCast};
pub fn window_event_listener<'a>(
event_name: &'a str,
cb: impl Fn(web_sys::Event) + 'static,
) -> impl FnOnce() -> () + 'a {
let handler = Box::new(cb) as Box<dyn FnMut(web_sys::Event)>;
let cb = Closure::wrap(handler).into_js_value();
_ = window().add_event_listener_with_callback(event_name, cb.unchecked_ref());
pub fn window_event_listener<E: ev::EventDescriptor + 'static>(
event: E,
cb: impl Fn(E::EventType) + 'static,
) -> impl FnOnce() -> ()
where
E::EventType: JsCast,
{
fn wel(
cb: Box<dyn FnMut(web_sys::Event)>,
event_name: Cow<'static, str>,
) -> impl FnOnce() -> () + 'static {
let cb = Closure::wrap(cb).into_js_value();
_ = window().add_event_listener_with_callback(&event_name, cb.unchecked_ref());
move || {
_ = window().remove_event_listener_with_callback(event_name, cb.unchecked_ref());
_ = window().remove_event_listener_with_callback(&event_name, cb.unchecked_ref());
}
}
wel(
Box::new(move |e| cb(e.unchecked_into::<E::EventType>())),
event.name(),
)
}