-
Notifications
You must be signed in to change notification settings - Fork 253
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How do I attach a function to window? #230
Comments
Currently there isn't a way to access the generated wasm manually. Trunk automatically injects that first Instead, you can set |
Is there any snippets your can share on this? I tried this: use js_sys::Reflect;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn my_function() -> Result<(), JsValue> {
Ok(())
}
fn main() {
let window = web_sys::window().expect("no global `window` exists");
Reflect::set(&window, &"my_function".into(), &my_function.into())
.expect("Failed reflecting my_function.");
} But I got:
|
Ah yes, you must create a Closure instead and cast it into a |
Otherwise, you could use the snippets system (https://trunkrs.dev/assets/#js-snippets) and pass along a Rust/WASM function for the JS function to use. Not 100% sure what your requirements are. Perhaps describing what your ultimate goal is will help folks to find a viable solution. |
Wow I literally don't understand a single word in this pile of whatever: Closure::wrap(Box::new(|| {
web_sys::console::log_1(&"inverval elapsed!".into());
}) as Box<dyn FnMut()>).as_ref().unchecked_ref(),; I eventually go with this: #[wasm_bindgen]
pub struct Wrapper {}
#[wasm_bindgen]
impl Wrapper {
#[wasm_bindgen]
pub fn my_function(&self) -> Result<(), JsValue> {
Ok(())
}
}
fn main() {
Reflect::set(
&web_sys::window().unwrap(),
&JsValue::from("wrapper"),
&JsValue::from(Wrapper {}),
)
.unwrap();
} And use it like this: <script>
window.wrapper.my_function();
</script> Yea, as long as it works. |
@WestXu yea, until browsers start exposing a more direct WASM ABI with something similar to WASI, the browser ABI will have this rough FFI feel to it. Lots of frameworks offer a slightly nicer pattern on top of this, but ultimately you are passing a boxed fn as a closure. |
I won't blame it though. This project is amazing already. I'm happy with what it is doing now. Feel free to close it. |
Sounds good! Thanks for the discussion and sharing your findings. |
Newbie here.
Previously I use wasm-pack doing this:
What's the equivalent
pub fn main()
using trunk?And if this is not the right way to call wasm function from js, what is?
The text was updated successfully, but these errors were encountered: