leptos-use/examples/use_mutation_observer/src/main.rs

63 lines
1.8 KiB
Rust
Raw Normal View History

2023-07-03 16:10:58 +01:00
use leptos::html::Div;
2023-06-13 00:31:38 +01:00
use leptos::*;
use leptos_use::docs::demo_or_body;
use leptos_use::{use_mutation_observer_with_options, UseMutationObserverOptions};
2023-06-13 00:31:38 +01:00
use std::time::Duration;
#[component]
2023-07-27 18:06:36 +01:00
fn Demo() -> impl IntoView {
let el = create_node_ref::<Div>();
let (messages, set_messages) = create_signal(vec![]);
let (class_name, set_class_name) = create_signal(String::new());
let (style, set_style) = create_signal(String::new());
2023-06-13 00:31:38 +01:00
use_mutation_observer_with_options(
el,
move |mutations, _| {
if let Some(mutation) = mutations.first() {
set_messages.update(move |messages| {
messages.push(format!("{:?}", mutation.attribute_name()));
});
}
},
UseMutationObserverOptions::default().attributes(true),
2023-06-13 00:31:38 +01:00
);
let _ = set_timeout_with_handle(
move || {
set_class_name.set("test test2".to_string());
2023-06-13 00:31:38 +01:00
},
Duration::from_millis(1000),
);
let _ = set_timeout_with_handle(
move || {
set_style.set("color: red;".to_string());
2023-06-13 00:31:38 +01:00
},
Duration::from_millis(1550),
);
2023-07-27 18:06:36 +01:00
let enum_msgs =
Signal::derive(move || messages.get().into_iter().enumerate().collect::<Vec<_>>());
2023-06-13 00:31:38 +01:00
2023-07-27 19:48:21 +01:00
view! {
<div node_ref=el class=move || class_name.get() style=move || style.get()>
2023-06-13 00:31:38 +01:00
<For
each=move || enum_msgs.get()
2023-07-27 19:48:21 +01:00
// list only grows so this is fine here
key=|message| message.0
2023-07-27 18:06:36 +01:00
view=|message| view! { <div>"Mutation Attribute: " <code>{message.1}</code></div> }
2023-06-13 00:31:38 +01:00
/>
</div>
}
}
fn main() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
2023-07-27 18:06:36 +01:00
mount_to(demo_or_body(), || {
2023-07-27 19:48:21 +01:00
view! { <Demo/> }
2023-06-13 00:31:38 +01:00
})
}