Skip to content

Commit

Permalink
Add Section On Async EventHandlers (#275)
Browse files Browse the repository at this point in the history
* feat: async event handler section

* fix: doc tests
  • Loading branch information
DogeDark authored May 21, 2024
1 parent 2bb1054 commit 8d6bc05
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
7 changes: 7 additions & 0 deletions docs-src/0.5/en/reference/event_handlers.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ Then, you can use it like any other handler:

> Note: just like any other attribute, you can name the handlers anything you want! Any closure you pass in will automatically be turned into an `EventHandler`.
#### Async Event Handlers
Passing `EventHandler`s as props does not support passing a closure that returns an async block. Instead, you must manually call ``spawn`` to do async operations:
```rust, no_run
{{#include src/doc_examples/event_handler_prop.rs:async}}
```
This is only the case for custom event handlers as props.

## Custom Data

Event Handlers are generic over any type, so you can pass in any data you want to them, e.g:
Expand Down
26 changes: 25 additions & 1 deletion src/doc_examples/event_handler_prop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ fn main() {

fn App() -> Element {
// ANCHOR: usage
rsx! { FancyButton { onclick: move |event| println!("Clicked! {event:?}") } }
rsx! {
FancyButton {
onclick: move |event| println!("Clicked! {event:?}"),
}
}
// ANCHOR_END: usage
}

Expand Down Expand Up @@ -47,3 +51,23 @@ pub fn CustomFancyButton(props: CustomFancyButtonProps) -> Element {
}
}
// ANCHOR_END: custom_data

pub fn MyComponent() -> Element {
// ANCHOR: async
rsx! {
FancyButton {
// This does not work!
// onclick: move |event| async move {
// println!("Clicked! {event:?}");
// },

// This does work!
onclick: move |event| {
spawn(async move {
println!("Clicked! {event:?}");
});
},
}
}
// ANCHOR_END: async
}

0 comments on commit 8d6bc05

Please sign in to comment.