floem/views/editor/
listener.rs1use floem_reactive::{RwSignal, Scope, SignalGet, SignalUpdate};
2
3#[derive(Debug)]
10pub struct Listener<T: 'static> {
11 cx: Scope,
12 val: RwSignal<Option<T>>,
13}
14
15impl<T: Clone + 'static> Listener<T> {
16 pub fn new(cx: Scope, on_val: impl Fn(T) + 'static) -> Listener<T> {
17 let val = cx.create_rw_signal(None);
18
19 let listener = Listener { val, cx };
20 listener.listen(on_val);
21
22 listener
23 }
24
25 pub fn new_empty(cx: Scope) -> Listener<T> {
29 let val = cx.create_rw_signal(None);
30 Listener { val, cx }
31 }
32
33 pub fn scope(&self) -> Scope {
34 self.cx
35 }
36
37 pub fn listen(self, on_val: impl Fn(T) + 'static) {
39 self.listen_with(self.cx, on_val)
40 }
41
42 pub fn listen_with(self, cx: Scope, on_val: impl Fn(T) + 'static) {
46 let val = self.val;
47
48 cx.create_effect(move |_| {
49 if let Some(cmd) = val.get() {
51 on_val(cmd);
52 }
53 });
54 }
55
56 pub fn send(&self, v: T) {
58 self.val.set(Some(v));
59 }
60}
61
62impl<T: 'static> Copy for Listener<T> {}
63
64impl<T: 'static> Clone for Listener<T> {
65 fn clone(&self) -> Self {
66 *self
67 }
68}