all_events.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. //! This example shows how to listen to all events on a div and log them to the console.
  2. //!
  3. //! The primary demonstration here is the properties on the events themselves, hoping to give you some inspiration
  4. //! on adding interactivity to your own application.
  5. use dioxus::prelude::*;
  6. use std::{collections::VecDeque, fmt::Debug, rc::Rc};
  7. const STYLE: &str = asset!("./examples/assets/events.css");
  8. fn main() {
  9. launch(app);
  10. }
  11. fn app() -> Element {
  12. // Using a VecDeque so its cheap to pop old events off the front
  13. let mut events = use_signal(VecDeque::new);
  14. // All events and their data implement Debug, so we can re-cast them as Rc<dyn Debug> instead of their specific type
  15. let mut log_event = move |event: Rc<dyn Debug>| {
  16. // Only store the last 20 events
  17. if events.read().len() >= 20 {
  18. events.write().pop_front();
  19. }
  20. events.write().push_back(event);
  21. };
  22. rsx! {
  23. head::Link { rel: "stylesheet", href: STYLE }
  24. div { id: "container",
  25. // focusing is necessary to catch keyboard events
  26. div { id: "receiver", tabindex: 0,
  27. onmousemove: move |event| log_event(event.data()),
  28. onclick: move |event| log_event(event.data()),
  29. ondoubleclick: move |event| log_event(event.data()),
  30. onmousedown: move |event| log_event(event.data()),
  31. onmouseup: move |event| log_event(event.data()),
  32. onwheel: move |event| log_event(event.data()),
  33. onkeydown: move |event| log_event(event.data()),
  34. onkeyup: move |event| log_event(event.data()),
  35. onkeypress: move |event| log_event(event.data()),
  36. onfocusin: move |event| log_event(event.data()),
  37. onfocusout: move |event| log_event(event.data()),
  38. "Hover, click, type or scroll to see the info down below"
  39. }
  40. div { id: "log",
  41. for event in events.read().iter() {
  42. div { "{event:?}" }
  43. }
  44. }
  45. }
  46. }
  47. }