1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use crate::app::MessageMapper;
use crate::virtual_dom::Ev;
use std::{fmt, rc::Rc};
pub struct EventHandler<Ms> {
pub trigger: Ev,
pub callback: Rc<dyn Fn(web_sys::Event) -> Option<Ms>>,
}
impl<Ms> Clone for EventHandler<Ms> {
fn clone(&self) -> Self {
Self {
trigger: self.trigger.clone(),
callback: Rc::clone(&self.callback),
}
}
}
impl<Ms> EventHandler<Ms> {
pub fn new(
trigger: impl Into<Ev>,
callback: impl Fn(web_sys::Event) -> Option<Ms> + 'static,
) -> Self {
Self {
trigger: trigger.into(),
callback: Rc::new(callback),
}
}
}
impl<Ms: 'static, OtherMs: 'static> MessageMapper<Ms, OtherMs> for EventHandler<Ms> {
type SelfWithOtherMs = EventHandler<OtherMs>;
fn map_msg(
self,
msg_mapper: impl FnOnce(Ms) -> OtherMs + 'static + Clone,
) -> EventHandler<OtherMs> {
let old_callback = self.callback;
let new_callback = move |event| {
let msg_mapper = msg_mapper.clone();
old_callback(event).map(msg_mapper)
};
EventHandler {
trigger: self.trigger,
callback: Rc::new(new_callback),
}
}
}
impl<Ms> fmt::Debug for EventHandler<Ms> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "EventHandler('{}')", self.trigger.as_str())
}
}