Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::cell::RefCell;
- mod web_sys {
- pub struct Window;
- pub struct SomeEventListener;
- pub struct CanvasRenderingContext2d;
- impl CanvasRenderingContext2d {
- pub fn fill_rect(&self, x: f64, y: f64, w: f64, h: f64) {
- unimplemented!()
- }
- }
- }
- thread_local! {
- // If you don't need mutability in `Ctx`, you don't need to use `RefCell`
- static CTX: RefCell<Option<Ctx>> = RefCell::new(None);
- }
- struct Ctx {
- pub window: web_sys::Window,
- pub events: Vec<web_sys::SomeEventListener>,
- pub render: web_sys::CanvasRenderingContext2d,
- }
- impl Ctx {
- fn new() -> Ctx {
- Ctx {
- window: web_sys::Window,
- events: vec![],
- render: web_sys::CanvasRenderingContext2d,
- }
- }
- }
- fn main() {
- // Init
- let ctx = Ctx::new();
- CTX.with(|cell| cell.replace(Some(ctx)));
- // Run
- call_draw_player(0., 0.);
- }
- // #[wasm_bindgen]
- fn call_draw_player(x: f64, y: f64) {
- // Can also call `borrow_mut` with `RefCell`
- CTX.with(|ctx| draw_player(ctx.borrow().as_ref().unwrap(), x, y))
- }
- fn draw_player(ctx: &Ctx, x: f64, y: f64) {
- ctx.render.fill_rect(x, y, 100., 100.);
- }
- /*
- NOTE: We could use this:
- ```
- impl Ctx {
- fn draw_player(&self, ...) { ... }
- }
- // ...later...
- ctx.draw_player(...);
- ```
- However, this can get dirty really quickly since you often need to use `Ctx` on
- an impl for another item. Imagine:
- ```
- struct GameManager;
- impl GameManager {
- fn draw_player(&self, ctx: &Ctx) {
- ctx.render.fill_rect(...);
- }
- }
- ```
- For really really common functions, then yeah, put that in an `impl Ctx`, but
- other less common or domain-specific functionality should be either a global
- function or implemented on its appropriate struct.
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement