Skip to content

Commit

Permalink
Merge pull request rustwasm#1044 from ibaryshnikov/dom-example-withou…
Browse files Browse the repository at this point in the history
…t-bundlers

Added web-sys dom example withot npm and webpack
  • Loading branch information
alexcrichton authored Nov 27, 2018
2 parents a202f1c + 873898e commit 6fd33a7
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 19 deletions.
10 changes: 10 additions & 0 deletions examples/no_modules/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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',
]
22 changes: 9 additions & 13 deletions examples/no_modules/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -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>
21 changes: 15 additions & 6 deletions examples/no_modules/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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(())
}

0 comments on commit 6fd33a7

Please sign in to comment.