Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. use std::cell::RefCell;
  2.  
  3. mod web_sys {
  4. pub struct Window;
  5.  
  6. pub struct SomeEventListener;
  7.  
  8. pub struct CanvasRenderingContext2d;
  9.  
  10. impl CanvasRenderingContext2d {
  11. pub fn fill_rect(&self, x: f64, y: f64, w: f64, h: f64) {
  12. unimplemented!()
  13. }
  14. }
  15. }
  16.  
  17. thread_local! {
  18. // If you don't need mutability in `Ctx`, you don't need to use `RefCell`
  19. static CTX: RefCell<Option<Ctx>> = RefCell::new(None);
  20. }
  21.  
  22. struct Ctx {
  23. pub window: web_sys::Window,
  24. pub events: Vec<web_sys::SomeEventListener>,
  25. pub render: web_sys::CanvasRenderingContext2d,
  26. }
  27.  
  28. impl Ctx {
  29. fn new() -> Ctx {
  30. Ctx {
  31. window: web_sys::Window,
  32. events: vec![],
  33. render: web_sys::CanvasRenderingContext2d,
  34. }
  35. }
  36. }
  37.  
  38. fn main() {
  39. let ctx = Ctx::new();
  40. draw_player(&ctx, 0., 0.);
  41. }
  42.  
  43. // #[wasm_bindgen]
  44. fn call_draw_player(x: f64, y: f64) {
  45. // Can also call `borrow_mut` with `RefCell`
  46. CTX.with(|ctx| draw_player(ctx.borrow().as_ref().unwrap(), x, y))
  47. }
  48.  
  49. fn draw_player(ctx: &Ctx, x: f64, y: f64) {
  50. ctx.render.fill_rect(x, y, 100., 100.);
  51. }
  52.  
  53.  
  54. /*
  55.  
  56. NOTE: We could use this:
  57.  
  58. ```
  59. impl Ctx {
  60. fn draw_player(&self, ...) { ... }
  61. }
  62.  
  63. // ...later...
  64.  
  65. ctx.draw_player(...);
  66. ```
  67.  
  68. However, this can get dirty really quickly since you often need to use `Ctx` on
  69. an impl for another item. Imagine:
  70.  
  71. ```
  72. struct GameManager;
  73.  
  74. impl GameManager {
  75. fn draw_player(&self, ctx: &Ctx) {
  76. ctx.render.fill_rect(...);
  77. }
  78. }
  79. ```
  80.  
  81. For really really common functions, then yeah, put that in an `impl Ctx`, but
  82. other less common or domain-specific functionality should be either a global
  83. function or implemented on its appropriate struct.
  84.  
  85. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement