hirola_core/
callback.rs

1use futures_signals::{signal::Mutable, signal_vec::MutableVec};
2
3/// Allows a shorthand for creating event listeners.
4/// Mainly useful in event emitting nodes
5pub trait Callback<E = ()>: Clone + 'static {
6    /// Pass a callback that allows interacting with the inner value and the event
7    /// This method returns the new value and this updates the signal.
8    fn callback_with<F>(&self, f: F) -> Box<dyn Fn(E) + 'static>
9    where
10        F: Fn(&Self, E) + 'static,
11    {
12        let state = self.clone();
13        let cb = move |e| {
14            f(&state, e);
15        };
16        Box::new(cb)
17    }
18    /// Pass a callback that allows interacting with self and the event
19    fn callback<F>(&self, f: F) -> Box<dyn Fn(E) + 'static>
20    where
21        F: Fn(&Self) + 'static,
22    {
23        let state = self.clone();
24        let cb = move |_| {
25            f(&state);
26        };
27        Box::new(cb)
28    }
29}
30
31impl<T: Clone + 'static, E> Callback<E> for Mutable<T> {}
32
33impl<T: Clone + 'static, E> Callback<E> for MutableVec<T> {}