@@ -3,30 +3,37 @@ use dodrio::{on, Node, Render};
4use wasm_bindgen::prelude::*;
4use wasm_bindgen::prelude::*;
6+/// A counter that can be incremented and decrmented!
6struct Counter {
7struct Counter {
7โ val: isize,
8+ count: isize,
10impl Counter {
11impl Counter {
12+ /// Construct a new, zeroed counter.
11 fn new() -> Counter {
13 fn new() -> Counter {
12โ Counter { val: 0 }
14+ Counter { count: 0 }
17+ /// Increment this counter's count.
15 fn increment(&mut self) {
18 fn increment(&mut self) {
16โ self.val += 1;
19+ self.count += 1;
22+ /// Decrement this counter's count.
19 fn decrement(&mut self) {
23 fn decrement(&mut self) {
20โ self.val -= 1;
24+ self.count -= 1;
28+// The `Render` implementation for `Counter`s displays the current count and has
29+// buttons to increment and decrement the count.
24impl Render for Counter {
30impl Render for Counter {
25 fn render<'a, 'bump>(&'a self, bump: &'bump Bump) -> dodrio::Node<'bump>
31 fn render<'a, 'bump>(&'a self, bump: &'bump Bump) -> dodrio::Node<'bump>
27 'a: 'bump,
33 'a: 'bump,
35+ // Stringify the count as a bump-allocated string.
29โ let val = bumpalo::format!(in bump, "{}", self.val);
36+ let count = bumpalo::format!(in bump, "{}", self.count);
31 Node::element(
38 Node::element(
@@ -38,17 +45,26 @@ impl Render for Counter {
40 [on(bump, "click", |root, vdom, _event| {
47 [on(bump, "click", |root, vdom, _event| {
48+ // Cast the root render component to a `Counter`, since
49+ // we know that's what it is.
41โ root.unwrap_mut::<Counter>().increment();
50+ let counter = root.unwrap_mut::<Counter>();
52+ // Increment the counter.
55+ // Since the count has updated, we should re-render the
56+ // counter on the next animation frame.
42 vdom.schedule_render();
57 vdom.schedule_render();
45 [Node::text("+")],
60 [Node::text("+")],
47โ Node::text(val.into_bump_str()),
62+ Node::text(count.into_bump_str()),
48 Node::element(
63 Node::element(
51 [on(bump, "click", |root, vdom, _event| {
66 [on(bump, "click", |root, vdom, _event| {
67+ // Same as above, but decrementing instead of incrementing.
52 root.unwrap_mut::<Counter>().decrement();
68 root.unwrap_mut::<Counter>().decrement();
53 vdom.schedule_render();
69 vdom.schedule_render();
@@ -62,9 +78,11 @@ impl Render for Counter {
63#[wasm_bindgen(start)]
79#[wasm_bindgen(start)]
64pub fn run() {
80pub fn run() {
81+ // Initialize debug logging for if/when things go wrong.
65 console_error_panic_hook::set_once();
82 console_error_panic_hook::set_once();
66 console_log::init_with_level(Level::Trace).expect("should initialize logging OK");
83 console_log::init_with_level(Level::Trace).expect("should initialize logging OK");
85+ // Get the document's `<body>`.
68 let window = web_sys::window().unwrap();
86 let window = web_sys::window().unwrap();
69 let document = window.document().unwrap();
87 let document = window.document().unwrap();
70 let body = document.body().unwrap();
88 let body = document.body().unwrap();