From e2f6780de42f0f2625422620d88de7289d2fc1d6 Mon Sep 17 00:00:00 2001 From: Marc-Stefan Cassola Date: Tue, 24 Oct 2023 19:14:51 +0100 Subject: [PATCH] docs: added `Callback` to documentation and examples. (#1926) * added Callback to documentation and examples. Also reduced code duplication in Callback implementation. * added back the closure event callback example --- docs/book/src/view/08_parent_child.md | 44 +++++++++- examples/counters/rust-toolchain.toml | 3 + .../client/src/components/navbar.rs | 13 ++- .../client/src/lib.rs | 2 +- .../client/src/pages/login.rs | 11 ++- examples/parent_child/rust-toolchain.toml | 3 + examples/parent_child/src/lib.rs | 22 +---- leptos_reactive/Cargo.toml | 1 + leptos_reactive/src/callback.rs | 82 ++++++++----------- 9 files changed, 97 insertions(+), 84 deletions(-) create mode 100644 examples/counters/rust-toolchain.toml create mode 100644 examples/parent_child/rust-toolchain.toml diff --git a/docs/book/src/view/08_parent_child.md b/docs/book/src/view/08_parent_child.md index 4d9b526c96..ffd0126cf9 100644 --- a/docs/book/src/view/08_parent_child.md +++ b/docs/book/src/view/08_parent_child.md @@ -72,9 +72,7 @@ pub fn App() -> impl IntoView { #[component] -pub fn ButtonB(on_click: F) -> impl IntoView -where - F: Fn(MouseEvent) + 'static, +pub fn ButtonB(#[prop(into)] on_click: Callback) -> impl IntoView { view! { + } +} +``` + +The code is very similar in this case. On more advanced use-cases using a +closure might require some cloning compared to using a `Callback`. + > Note the way we declare the generic type `F` here for the callback. If you’re > confused, look back at the [generic props](./03_components.html#generic-props) section > of the chapter on components. + ## 3. Use an Event Listener You can actually write Option 2 in a slightly different way. If the callback maps directly onto diff --git a/examples/counters/rust-toolchain.toml b/examples/counters/rust-toolchain.toml new file mode 100644 index 0000000000..e9743fb495 --- /dev/null +++ b/examples/counters/rust-toolchain.toml @@ -0,0 +1,3 @@ + +[toolchain] +channel = "nightly" diff --git a/examples/login_with_token_csr_only/client/src/components/navbar.rs b/examples/login_with_token_csr_only/client/src/components/navbar.rs index df18c4c9d7..af5b4164c9 100644 --- a/examples/login_with_token_csr_only/client/src/components/navbar.rs +++ b/examples/login_with_token_csr_only/client/src/components/navbar.rs @@ -3,10 +3,10 @@ use leptos::*; use leptos_router::*; #[component] -pub fn NavBar(logged_in: Signal, on_logout: F) -> impl IntoView -where - F: Fn() + 'static + Clone, -{ +pub fn NavBar( + logged_in: Signal, + #[prop(into)] on_logout: Callback<()>, +) -> impl IntoView { view! {