|
| 1 | +# `js-sys` |
| 2 | + |
| 3 | +The [`js-sys` crate][js-sys] provides raw bindings to all the global APIs |
| 4 | +guaranteed to exist in every JavaScript environment by the ECMAScript standard, |
| 5 | +and its source lives at [`wasm-bindgen/crates/js-sys`][src]. With the `js-sys` |
| 6 | +crate, we can work with `Object`s, `Array`s, `Function`s, `Map`s, `Set`s, |
| 7 | +etc... without writing the `#[wasm_bindgen]` imports by hand. |
| 8 | + |
| 9 | +Documentation for this crate will eventually be available on [docs.rs][docsrs] |
| 10 | +but temporarily you can also check out the [master branch |
| 11 | +documentation][masterdoc] for the crate. |
| 12 | + |
| 13 | +[docsrs]: https://docs.rs/js-sys |
| 14 | +[masterdoc]: https://rustwasm.github.io/wasm-bindgen/api/js_sys/ |
| 15 | +[src]: https://github.com/rustwasm/wasm-bindgen/tree/master/crates/js-sys |
| 16 | + |
| 17 | +For example, we can invoke JavaScript [`Function`][mdn-function] callbacks and |
| 18 | +time how long they take to execute with [`Date.now()`][mdn-date-now], and we |
| 19 | +don't need to write any JS imports ourselves: |
| 20 | + |
| 21 | +```rust |
| 22 | +extern crate js_sys; |
| 23 | +extern crate wasm_bindgen; |
| 24 | +use wasm_bindgen::prelude::*; |
| 25 | + |
| 26 | +#[wasm_bindgen] |
| 27 | +pub fn timed(callback: &js_sys::Function) -> f64 { |
| 28 | + let then = js_sys::Date::now(); |
| 29 | + callback.apply(JsValue::null(), &js_sys::Array::new()).unwrap(); |
| 30 | + let now = js_sys::Date::now(); |
| 31 | + now - then |
| 32 | +} |
| 33 | +``` |
| 34 | + |
| 35 | +The `js-sys` crate isn't quite 100% feature complete yet. There are still some |
| 36 | +JavaScript types and methods that we don't have bindings for. If you'd like to |
| 37 | +help out check out [the contribution documentation][contrib]. |
| 38 | + |
| 39 | +Also, as mentioned above, the `js-sys` crate doesn't contain bindings to any Web |
| 40 | +APIs like [`document.querySelectorAll`][mdn-qsa]. These will be part of the |
| 41 | +[`web-sys`](./web-sys.html) crate. |
| 42 | + |
| 43 | +[MDN]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects |
| 44 | +[js-sys]: https://crates.io/crates/js-sys |
| 45 | +[issue]: https://github.com/rustwasm/wasm-bindgen/issues/275 |
| 46 | +[mdn-function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function |
| 47 | +[mdn-qsa]: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll |
| 48 | +[web-sys-contributing]: https://rustwasm.github.io/wasm-bindgen/web-sys.html |
| 49 | +[web-sys-issues]: https://github.com/rustwasm/wasm-bindgen/issues?q=is%3Aissue+is%3Aopen+label%3Aweb-sys |
| 50 | +[mdn-date-now]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now |
| 51 | +[contrib]: https://github.com/rustwasm/wasm-bindgen/issues/275 |
0 commit comments