Skip to content

Instantly share code, notes, and snippets.

@jsjolund
Created October 16, 2022 13:29
Show Gist options
  • Save jsjolund/dc7029650bf2b4fbb7787e93b64556dc to your computer and use it in GitHub Desktop.
Save jsjolund/dc7029650bf2b4fbb7787e93b64556dc to your computer and use it in GitHub Desktop.
[package]
edition = "2021"
name = "hello-wasm"
version = "0.1.0"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
js-sys = "0.3"
wasm-bindgen = "0.2"
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>hello-wasm example</title>
</head>
<body>
<script type="module">
import init, { main } from "./pkg/hello_wasm.js";
init().then(() => {
main();
});
</script>
</body>
</html>
use wasm_bindgen::{prelude::*, JsCast};
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
macro_rules! console_log {
($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
}
#[wasm_bindgen]
pub fn main() {
// Create an empty object
let obj = js_sys::Object::new();
console_log!("Object {:?}", obj);
// Firefox:
// Object { obj: JsValue(Object({})) }
// Set key and value as strings work:
let key = JsValue::from_str("key0");
let val = JsValue::from_str("val0");
let success = js_sys::Reflect::set(&obj, &key, &val).unwrap();
console_log!("Object {:?}, success {}", obj, success);
// Firefox:
// Object { obj: JsValue(Object({"key0":"val0"})) }, success true
// Set key as string and value as function does not:
let key = JsValue::from_str("key1");
let func: Closure<dyn Fn()> = Closure::wrap(Box::new(|| console_log!("hello from closure")));
let val = func.as_ref().dyn_ref().unwrap();
let success = js_sys::Reflect::set(&obj, &key, val).unwrap();
console_log!("Object {:?}, success {}", obj, success);
// Firefox:
// Object { obj: JsValue(Object({"key0":"val0"})) }, success true
// key1 is missing... although it is accessible
let res = js_sys::Reflect::get(&obj, &key).unwrap();
console_log!("Result {:?}", res);
// Firefox:
// Result JsValue(Function(real))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment