Pauan / rust-dominator

Zero-cost ultra-high-performance declarative DOM library using FRP signals for Rust!
MIT License
960 stars 62 forks source link

Other Events #32

Closed NeverGivinUp closed 4 years ago

NeverGivinUp commented 4 years ago

Currently rust-dominator has a great event mechanism but only few usable events.

The make_event macro is not exported. I tried manually expanding the macro for an event, but I'm neither getting an error message nor registering events, when I set up my events: .global_event(|_event: LoadEnd| { log!("LoadEndEvent registered") }).global_event(|_event: Load| { log!("LoadEvent registered") })

The Resize event, that you defined works: .global_event(|_event: Resize| { log!("ResizeEvent registered") })

Here's how I tried to expand them manually:

pub struct Load {
    event: web_sys::ProgressEvent
}

impl StaticEvent for Load {
    const EVENT_TYPE: &'static str = "load";

    #[inline]
    fn unchecked_from_event(event: web_sys::Event) -> Self {
        Self {
            event: event.unchecked_into(),
        }
    }
}

impl Load {
    #[inline]
    pub fn prevent_default(&self) { self.event.prevent_default(); }

    #[inline]
    pub fn target(&self) -> Option<EventTarget> { self.event.target() }

    #[inline]
    pub fn dyn_target<A>(&self) -> Option<A> where A: JsCast {
        self.target()?.dyn_into().ok()
    }
}

pub struct LoadEnd {
    event: web_sys::ProgressEvent
}

impl StaticEvent for LoadEnd {
    const EVENT_TYPE: &'static str = "loadend";

    #[inline]
    fn unchecked_from_event(event: web_sys::Event) -> Self {
        Self {
            event: event.unchecked_into(),
        }
    }
}

impl LoadEnd {
    #[inline]
    pub fn prevent_default(&self) { self.event.prevent_default(); }

    #[inline]
    pub fn target(&self) -> Option<EventTarget> { self.event.target() }

    #[inline]
    pub fn dyn_target<A>(&self) -> Option<A> where A: JsCast {
        self.target()?.dyn_into().ok()
    }
}
Pauan commented 4 years ago

This is covered by https://github.com/Pauan/rust-dominator/issues/24 which currently isn't possible because Rust doesn't have const generics yet.

As for your manual event, I don't see anything wrong with it, so it's probably just because the load event has already finished before your Rust code runs.

Because of that, I don't recommend using events for load, instead it's better to use a Future or Signal, such as is_window_loaded, which will be true if the window is loaded.