rustwasm / book

The Rust and WebAssembly Book
https://rustwasm.github.io/docs/book/
MIT License
1.73k stars 208 forks source link

Better explanation of closures and a websocket example #151

Open ApoorvaJ opened 5 years ago

ApoorvaJ commented 5 years ago

The current documentation on closures requires a lot of prior knowledge of Rust, closures, and of this library. The relationship between JsValue, Function and a Closure isn't properly explained. An understanding of Fn and FnMut is also assumed.

I spent quite a lot of time fighting the borrow checker because my values would be moved into the closure. Without closures, I understand the Rust borrow checker pretty well, and I have done significant systems programming in the past, so the Rust model lines up with good C code. But this understanding breaks with closures.

Additionally, the documentation doesn't discuss how to get values in closures that would be passed into Javascript event callbacks, e.g.

websocket.onmessage = function(msg) {
    // use `msg`
};

How do I get msg in Rust-land?

Having a WebSocket example such as the one stdweb has would be a nice illustration of the websocket APIs, and coupled with a better explanation of closures, would also clarify that matter greatly.

ApoorvaJ commented 5 years ago

I've figured out how closures work, and how to work with websockets, but I think that some things need better explanation:

  1. The relationship between JsValue, Function and a Closure.
  2. Why the rather un-ergonomic Closure pattern is required, and what Closure.forget() means.
  3. How the different add_event_listener... functions work.
  4. How/why they differ from set_on* functions such as WebSocket::set_onopen().
  5. If we can pull into the docs the event types that are passed to closures, e.g. web_sys::MouseEvent, that would be helpful. Currently we have to do a lot of ping-ponging between web_sys docs and MDN.
  6. An explanation of how closures retain ownership of the data not obviously passed to the closure, and how to clone() things as required.