wasm-bindgen/guide/src/js-sys.md
2018-07-26 17:56:55 -07:00

2.3 KiB

js-sys

The js-sys crate provides raw bindings to all the global APIs guaranteed to exist in every JavaScript environment by the ECMAScript standard, and its source lives at wasm-bindgen/crates/js-sys. With the js-sys crate, we can work with Objects, Arrays, Functions, Maps, Sets, etc... without writing the #[wasm_bindgen] imports by hand.

Documentation for this crate will eventually be available on docs.rs but temporarily you can also check out the master branch documentation for the crate.

For example, we can invoke JavaScript Function callbacks and time how long they take to execute with Date.now(), and we don't need to write any JS imports ourselves:

extern crate js_sys;
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn timed(callback: &js_sys::Function) -> f64 {
    let then = js_sys::Date::now();
    callback.apply(JsValue::null(), &js_sys::Array::new()).unwrap();
    let now = js_sys::Date::now();
    now - then
}

The js-sys crate isn't quite 100% feature complete yet. There are still some JavaScript types and methods that we don't have bindings for. If you'd like to help out check out the contribution documentation.

Also, as mentioned above, the js-sys crate doesn't contain bindings to any Web APIs like document.querySelectorAll. These will be part of the web-sys crate.