Skip to main content

react_rs_elements/
events.rs

1pub struct Event {
2    pub event_type: String,
3    pub target_value: Option<String>,
4    pub checked: Option<bool>,
5}
6
7impl Event {
8    pub fn new(event_type: impl Into<String>) -> Self {
9        Self {
10            event_type: event_type.into(),
11            target_value: None,
12            checked: None,
13        }
14    }
15
16    pub fn with_target_value(mut self, value: String) -> Self {
17        self.target_value = Some(value);
18        self
19    }
20
21    pub fn with_checked(mut self, checked: bool) -> Self {
22        self.checked = Some(checked);
23        self
24    }
25
26    pub fn value(&self) -> &str {
27        self.target_value.as_deref().unwrap_or("")
28    }
29}
30
31pub struct EventHandler {
32    pub event_type: String,
33    handler: std::rc::Rc<dyn Fn(Event)>,
34}
35
36impl EventHandler {
37    pub fn new<F>(event_type: impl Into<String>, handler: F) -> Self
38    where
39        F: Fn(Event) + 'static,
40    {
41        Self {
42            event_type: event_type.into(),
43            handler: std::rc::Rc::new(handler),
44        }
45    }
46
47    pub fn event_type(&self) -> &str {
48        &self.event_type
49    }
50
51    pub fn invoke(&self, event: Event) {
52        (self.handler)(event);
53    }
54
55    pub fn take_handler_rc(&self) -> std::rc::Rc<dyn Fn(Event)> {
56        self.handler.clone()
57    }
58}