mirror of
https://github.com/rustwasm/wasm-bindgen.git
synced 2025-01-05 19:53:55 +03:00
updated no_modules example to show web-sys usage
This commit is contained in:
parent
091eaa66f3
commit
873898e6c0
@ -8,3 +8,13 @@ crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
wasm-bindgen = "0.2.28"
|
||||
|
||||
[dependencies.web-sys]
|
||||
version = "0.3.4"
|
||||
features = [
|
||||
'Document',
|
||||
'Element',
|
||||
'HtmlElement',
|
||||
'Node',
|
||||
'Window',
|
||||
]
|
||||
|
@ -20,19 +20,15 @@
|
||||
<script src='./no_modules.js'></script>
|
||||
|
||||
<script>
|
||||
// the `wasm_bindgen` global is set to the exports of the Rust module
|
||||
const { greet } = wasm_bindgen;
|
||||
|
||||
// we'll defer our execution until the wasm is ready to go
|
||||
function run() {
|
||||
greet('World');
|
||||
}
|
||||
|
||||
// here we tell bindgen the path to the wasm file so it can run
|
||||
// initialization and return to us a promise when it's done
|
||||
wasm_bindgen('./no_modules_bg.wasm')
|
||||
.then(run)
|
||||
.catch(console.error);
|
||||
window.addEventListener('load', async () => {
|
||||
// the `wasm_bindgen` global is set to the exports of the Rust module
|
||||
//
|
||||
// here we tell bindgen the path to the wasm file so it can run
|
||||
// initialization and return to us a promise when it's done
|
||||
// also, we can use 'await' on the returned promise
|
||||
await wasm_bindgen('./no_modules_bg.wasm');
|
||||
wasm_bindgen.run();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
@ -1,13 +1,22 @@
|
||||
extern crate wasm_bindgen;
|
||||
extern crate web_sys;
|
||||
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
// Called by our JS entry point to run the example
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
fn alert(s: &str);
|
||||
}
|
||||
pub fn run() -> Result<(), JsValue> {
|
||||
// Use `web_sys`'s global `window` function to get a handle on the global
|
||||
// window object.
|
||||
let window = web_sys::window().expect("no global `window` exists");
|
||||
let document = window.document().expect("should have a document on window");
|
||||
let body = document.body().expect("document should have a body");
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn greet(name: &str) {
|
||||
alert(&format!("Hello, {}!", name));
|
||||
// Manufacture the element we're gonna append
|
||||
let val = document.create_element("p")?;
|
||||
val.set_inner_html("Hello from Rust!");
|
||||
|
||||
body.append_child(&val)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user