Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 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. // Init
  40. let ctx = Ctx::new();
  41. CTX.with(|cell| cell.replace(Some(ctx)));
  42.  
  43. // Run
  44. call_draw_player(0., 0.);
  45. }
  46.  
  47. // #[wasm_bindgen]
  48. fn call_draw_player(x: f64, y: f64) {
  49. // Can also call `borrow_mut` with `RefCell`
  50. CTX.with(|ctx| draw_player(ctx.borrow().as_ref().unwrap(), x, y))
  51. }
  52.  
  53. fn draw_player(ctx: &Ctx, x: f64, y: f64) {
  54. ctx.render.fill_rect(x, y, 100., 100.);
  55. }
  56.  
  57.  
  58. /*
  59.  
  60. NOTE: We could use this:
  61.  
  62. ```
  63. impl Ctx {
  64. fn draw_player(&self, ...) { ... }
  65. }
  66.  
  67. // ...later...
  68.  
  69. ctx.draw_player(...);
  70. ```
  71.  
  72. However, this can get dirty really quickly since you often need to use `Ctx` on
  73. an impl for another item. Imagine:
  74.  
  75. ```
  76. struct GameManager;
  77.  
  78. impl GameManager {
  79. fn draw_player(&self, ctx: &Ctx) {
  80. ctx.render.fill_rect(...);
  81. }
  82. }
  83. ```
  84.  
  85. For really really common functions, then yeah, put that in an `impl Ctx`, but
  86. other less common or domain-specific functionality should be either a global
  87. function or implemented on its appropriate struct.
  88.  
  89. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement