dioxus/examples/all_events.rs

56 lines
2 KiB
Rust
Raw Normal View History

2024-02-14 20:33:07 +00:00
//! This example shows how to listen to all events on a div and log them to the console.
//!
//! The primary demonstration here is the properties on the events themselves, hoping to give you some inspiration
//! on adding interactivity to your own application.
2024-01-31 01:59:57 +00:00
use dioxus::prelude::*;
2024-01-19 23:48:21 +00:00
use std::{collections::VecDeque, fmt::Debug, rc::Rc};
fn main() {
launch(app);
}
fn app() -> Element {
2024-02-14 20:33:07 +00:00
// Using a VecDeque so its cheap to pop old events off the front
2024-02-14 21:50:10 +00:00
let mut events = use_signal(VecDeque::new);
2024-02-14 20:33:07 +00:00
// All events and their data implement Debug, so we can re-cast them as Rc<dyn Debug> instead of their specific type
2024-01-19 23:48:21 +00:00
let mut log_event = move |event: Rc<dyn Debug>| {
2024-02-14 20:33:07 +00:00
// Only store the last 20 events
if events.read().len() >= 20 {
events.write().pop_front();
2022-07-03 03:17:48 +00:00
}
2024-02-14 20:33:07 +00:00
events.write().push_back(event);
2022-07-03 03:17:48 +00:00
};
2024-01-16 19:18:46 +00:00
rsx! {
2024-02-14 20:33:07 +00:00
style { {include_str!("./assets/events.css")} }
div { id: "container",
2024-01-19 23:48:21 +00:00
// focusing is necessary to catch keyboard events
2024-02-14 20:33:07 +00:00
div { id: "receiver", tabindex: 0,
2024-01-31 22:07:00 +00:00
onmousemove: move |event| log_event(event.data()),
onclick: move |event| log_event(event.data()),
ondoubleclick: move |event| log_event(event.data()),
onmousedown: move |event| log_event(event.data()),
onmouseup: move |event| log_event(event.data()),
2024-01-19 23:48:21 +00:00
2024-01-31 22:07:00 +00:00
onwheel: move |event| log_event(event.data()),
2024-01-19 23:48:21 +00:00
2024-01-31 22:07:00 +00:00
onkeydown: move |event| log_event(event.data()),
onkeyup: move |event| log_event(event.data()),
onkeypress: move |event| log_event(event.data()),
2024-01-19 23:48:21 +00:00
2024-01-31 22:07:00 +00:00
onfocusin: move |event| log_event(event.data()),
onfocusout: move |event| log_event(event.data()),
"Hover, click, type or scroll to see the info down below"
}
2024-02-14 20:33:07 +00:00
div { id: "log",
for event in events.read().iter() {
div { "{event:?}" }
}
}
}
2024-01-14 05:12:21 +00:00
}
}