@@ -3,30 +3,37 @@ use dodrio::{on, Node, Render};
33use log::*;
44use wasm_bindgen::prelude::*;
55
6+/// A counter that can be incremented and decrmented!
67struct Counter {
7− val: isize,
8+ count: isize,
89}
910
1011impl Counter {
12+ /// Construct a new, zeroed counter.
1113 fn new() -> Counter {
12− Counter { val: 0 }
14+ Counter { count: 0 }
1315 }
1416
17+ /// Increment this counter's count.
1518 fn increment(&mut self) {
16− self.val += 1;
19+ self.count += 1;
1720 }
1821
22+ /// Decrement this counter's count.
1923 fn decrement(&mut self) {
20− self.val -= 1;
24+ self.count -= 1;
2125 }
2226}
2327
28+// The `Render` implementation for `Counter`s displays the current count and has
29+// buttons to increment and decrement the count.
2430impl Render for Counter {
2531 fn render<'a, 'bump>(&'a self, bump: &'bump Bump) -> dodrio::Node<'bump>
2632 where
2733 'a: 'bump,
2834 {
29− let val = bumpalo::format!(in bump, "{}", self.val);
35+ // Stringify the count as a bump-allocated string.
36+ let count = bumpalo::format!(in bump, "{}", self.count);
3037
3138 Node::element(
3239 bump,
@@ -38,17 +45,26 @@ impl Render for Counter {
3845 bump,
3946 "button",
4047 [on(bump, "click", |root, vdom, _event| {
41− root.unwrap_mut::<Counter>().increment();
48+ // Cast the root render component to a `Counter`, since
49+ // we know that's what it is.
50+ let counter = root.unwrap_mut::<Counter>();
51+
52+ // Increment the counter.
53+ counter.increment();
54+
55+ // Since the count has updated, we should re-render the
56+ // counter on the next animation frame.
4257 vdom.schedule_render();
4358 })],
4459 [],
4560 [Node::text("+")],
4661 ),
47− Node::text(val.into_bump_str()),
62+ Node::text(count.into_bump_str()),
4863 Node::element(
4964 bump,
5065 "button",
5166 [on(bump, "click", |root, vdom, _event| {
67+ // Same as above, but decrementing instead of incrementing.
5268 root.unwrap_mut::<Counter>().decrement();
5369 vdom.schedule_render();
5470 })],
@@ -62,9 +78,11 @@ impl Render for Counter {
6278
6379#[wasm_bindgen(start)]
6480pub fn run() {
81+ // Initialize debug logging for if/when things go wrong.
6582 console_error_panic_hook::set_once();
6683 console_log::init_with_level(Level::Trace).expect("should initialize logging OK");
6784
85+ // Get the document's `<body>`.
6886 let window = web_sys::window().unwrap();
6987 let document = window.document().unwrap();
7088 let body = document.body().unwrap();