Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert Callback to be an enum to support Fn and FnOnce. #1125

Merged
merged 8 commits into from Apr 25, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions yew/src/callback.rs
Expand Up @@ -71,6 +71,15 @@ impl<IN> Callback<IN> {
};
}

/// Creates a callback from a FnOnce. You are responsible for ensuring
/// the callback is only called once otherwise it will panic.
pub fn callback_once<F>(func: F) -> Self
jstarry marked this conversation as resolved.
Show resolved Hide resolved
where
F: FnOnce(IN) + 'static
{
Callback::CallbackOnce(Rc::new(RefCell::new(Some(Box::new(func)))))
}

/// Creates a no-op callback which can be used when it is not suitable to use an
/// `Option<Callback>`.
pub fn noop() -> Self {
Expand Down
21 changes: 18 additions & 3 deletions yew/src/html/scope.rs
Expand Up @@ -119,7 +119,7 @@ impl<COMP: Component> Scope<COMP> {
self.update(ComponentUpdate::MessageBatch(messages));
}

/// This method creates a `Callback` which will send a message to the linked component's
/// Creates a `Callback` which will send a message to the linked component's
/// update method when invoked.
pub fn callback<F, IN, M>(&self, function: F) -> Callback<IN>
where
Expand All @@ -134,8 +134,23 @@ impl<COMP: Component> Scope<COMP> {
closure.into()
}

/// This method creates a `Callback` which will send a batch of messages back to the linked
/// component's update method when called.
/// Creates a `Callback` from a FnOnce which will send a message to the linked
/// component's update method when invoked.
pub fn callback_once<F, IN, M>(&self, function: F) -> Callback<IN>
where
M: Into<COMP::Message>,
F: FnOnce(IN) -> M + 'static,
{
let scope = self.clone();
let closure = move |input| {
let output = function(input);
scope.send_message(output);
};
Callback::callback_once(closure)
}

/// Creates a `Callback` which will send a batch of messages back to the linked
/// component's update method when invoked.
pub fn batch_callback<F, IN>(&self, function: F) -> Callback<IN>
where
F: Fn(IN) -> Vec<COMP::Message> + 'static,
Expand Down