Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hard to pass functions to web-sys #843

Closed
upsuper opened this issue Sep 17, 2018 · 1 comment

Comments

@upsuper
Copy link

@upsuper upsuper commented Sep 17, 2018

Tehe wasm-bindgen reference has a chapter for passing Rust closures to JS, which involves using Closure from wasm-bindgen.

However, functions exposed from web-sys doesn't seem to be using that. For example, Window::set_timeout_with_callback accepts a &Function which doesn't seem to have any conversion method with Closure, and it doesn't seem to be possible to construct a Function from Rust code (without writing JavaScript code inline).

It would be great if it is possible to pass Rust function or closure to web-sys functions which accept callbacks.

@afdw

This comment has been minimized.

Copy link
Collaborator

@afdw afdw commented Sep 17, 2018

Here is what you can do for now:

let closure: Closure<FnMut()> = Closure::new(|| {
    web_sys::console::log_1(&"Timeout".into());
});
web_sys::Window::set_timeout_with_callback_and_timeout_and_arguments_0(
    closure.as_ref().unchecked_ref(),
    3000,
).unwrap();
closure.forget();

See Paint for more examples.

alexcrichton added a commit to alexcrichton/wasm-bindgen that referenced this issue Sep 17, 2018
Show off usage of the stable `Closure::wrap` instead of `Closure::new` and
additionally add an explicit example of using it with `web_sys`.

Closes rustwasm#843
alexcrichton added a commit to alexcrichton/wasm-bindgen that referenced this issue Sep 18, 2018
Show off usage of the stable `Closure::wrap` instead of `Closure::new` and
additionally add an explicit example of using it with `web_sys`.

Closes rustwasm#843
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.