Skip to main content

wal_core/component/
callback.rs

1use std::{hash::Hash, rc::Rc};
2
3/// Callback is a wrapper around a function that is used to send messages to the [Component](../trait.Component.html).
4///
5/// `IN` is the type of the input of the wrapped function.
6/// Meaning if we would like to send a message to the [component](../trait.Component.html) we need to provide input of type `IN`.
7/// Callback should be used for defining child to parent [component](../trait.Component.html) communication and subscribing
8/// to HTML [events](../../events/index.html).
9pub struct Callback<IN> {
10    wrapper: Rc<dyn Fn(IN)>,
11}
12
13impl<IN> Callback<IN> {
14    /// Function that creates a new instance of the Callback.
15    /// Using a Callback defined by this function will not send [messages](../trait.Component.html#associatedtype.Message) to the [component](../trait.Component.html).
16    /// It should be used only if the Callback is to send [messages](../trait.Component.html#associatedtype.Message)
17    /// to the father [component](../trait.Component.html) and this logic should be contained in `wrapper` argument function.
18    /// If sending the [message](../trait.Component.html#associatedtype.Message) to the current [component](../trait.Component.html)
19    /// is the goal [create_callback](../behavior/trait.Behavior.html#tymethod.create_callback) function should be used.
20    pub fn new<F>(wrapper: F) -> Self
21    where
22        F: Fn(IN) + 'static,
23    {
24        Callback {
25            wrapper: Rc::new(wrapper),
26        }
27    }
28
29    /// Function that calls the [Callback] using the provided `input`.
30    pub fn emit(&self, input: IN) {
31        (self.wrapper)(input);
32    }
33}
34
35impl<IN> Hash for Callback<IN> {
36    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
37        let ptr = self.wrapper.as_ref() as *const dyn Fn(IN);
38        ptr.hash(state);
39    }
40}
41
42impl<IN> Clone for Callback<IN> {
43    fn clone(&self) -> Self {
44        Self {
45            wrapper: self.wrapper.clone(),
46        }
47    }
48}