How could this creation of a Function from a Closure be less verbose?

Hello Rustaceans,

I'm a new Rustacean :grin: and I'm into Rust + WASM.

How could this creation of a js_sys::Function from a wasm_bindgen::closure::Closure be less verbose?


use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use web_sys::{Window, window};

pub fn run() {
    let wind = Rc::new(window().unwrap() as Window);
    let wind1 = wind.clone();

    let mut update = Rc::new(RefCell::new(None));
    let update1 = update.clone();
    *update.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        wind1.request_animation_frame((update1.borrow().as_ref().unwrap() as &Closure<dyn Fn()>).as_ref().unchecked_ref());
    }) as Box<dyn Fn()>));
    wind.request_animation_frame((update.borrow().as_ref().unwrap() as &Closure<dyn Fn()>).as_ref().unchecked_ref());

corresponds to

function update() {


I can't read/understand it without basically writing it again and it was tedious to do so!
How could this be expressed more concisely or abstracted away from it?

It is greeting you,

There's a collection of crates called gloo which has some nice wrappers for stuff like this, including one called gloo-render specifically for requestAnimationFrame.

That said, if you look at the underlying code, it's basically the same as what you wrote above :slight_smile:


Thanks :heart_eyes: , this sounds exactly what I'm looking for. I am gonna take a look at it and most likely mark your answer as the solution.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.