Skip to main content

euv_core/event/handler/
impl.rs

1use crate::*;
2
3/// Implementation of event handler construction, cloning, and invocation.
4impl NativeEventHandler {
5    /// Creates a new event handler from an `NativeEventName` enum and callback.
6    ///
7    /// # Arguments
8    ///
9    /// - `NativeEventName` - The event name enum variant.
10    /// - `FnMut(NativeEvent) + 'static` - The callback to invoke when the event fires.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - A new event handler.
15    pub fn new<F>(event_name: NativeEventName, callback: F) -> Self
16    where
17        F: FnMut(NativeEvent) + 'static,
18    {
19        NativeEventHandler {
20            event_name: event_name.as_str().into_owned(),
21            callback: Rc::new(RefCell::new(callback)),
22        }
23    }
24
25    /// Invokes the underlying callback with the given event.
26    ///
27    /// # Arguments
28    ///
29    /// - `NativeEvent` - The event to pass to the callback.
30    pub fn handle(&self, event: NativeEvent) {
31        let mut cb: RefMut<dyn FnMut(NativeEvent)> = self.get_callback().borrow_mut();
32        cb(event);
33    }
34}
35
36/// Clones the event handler, sharing the underlying callback reference.
37impl Clone for NativeEventHandler {
38    /// Returns a clone of this handler sharing the same callback `Rc`.
39    fn clone(&self) -> Self {
40        NativeEventHandler {
41            event_name: self.get_event_name().clone(),
42            callback: Rc::clone(self.get_callback()),
43        }
44    }
45}