Skip to main content

euv_core/event/handler/
impl.rs

1use crate::*;
2
3/// Implementation of event handler construction and invocation.
4impl NativeEventHandler {
5    /// Creates a new event handler from a static event name string and callback.
6    ///
7    /// # Arguments
8    ///
9    /// - `&'static str` - The event name (e.g., "click", "input", "hashchange").
10    /// - `FnMut(Event) + 'static` - The callback to invoke when the event fires.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - A new event handler.
15    pub fn create<F>(event_name: &'static str, callback: F) -> Self
16    where
17        F: FnMut(Event) + 'static,
18    {
19        let callback: SharedEventCallback = Rc::new(UnsafeCell::new(Box::new(callback)));
20        Self::new(event_name, callback)
21    }
22
23    /// Invokes the underlying callback with the given event.
24    ///
25    /// # Safety
26    ///
27    /// Must only be called from the main thread. Guaranteed in WASM
28    /// single-threaded context. No concurrent access is possible.
29    ///
30    /// # Arguments
31    ///
32    /// - `Event` - The event to pass to the callback.
33    pub fn handle(&self, event: Event) {
34        let callback: &mut Box<dyn FnMut(Event)> = unsafe { &mut *self.get_callback().get() };
35        callback(event);
36    }
37}