I tried to pass a callback to the js method but currently it cannot be represented as WasmBoundary is not implemented.
So, what are the things that must be done to achieve an api as such:
#[wasm_bindgen]
extern {
type Element;
fn add_event_listener(this: &Element, ev_type: &str, listener: Box<FnMut()>);
}
Thanks for the report! This unfortunately isn't supported today, but we talked about this yesterday during the Berline all-hands and we think we've got a path forward! I'll leave some more comments soon when I get a chance.
Let me bug you once more. I wanted to know, whenever the callbacks are implemented, will we be able to pass a non-static lifetime bound closure?
For ex:
struct Apple {
value: i32
}
impl Apple {
fn gen_callback<'a>(&'a self) -> impl Fn() + 'a {
move || {
console::log(self.value);
}
}
}
That's definitely the plan yeah!
I'm starting to work on this now and I'll keep this issue updated with progress
I've started work on this in https://github.com/alexcrichton/wasm-bindgen/pull/101, although it's likely not quite ready yet to cover all use cases
As I understand it, event handler use cases are not supported currently as they require owned closures?
Also, you wrote that the you are gonna support 'static owned closures. Is non-static owned closures not feasible? I know that this will result in undefined reference kind of situation but the following on the user facing side could be done:
struct Apple {
value: i32
}
impl Apple {
fn gen_callback<'a>(&'a self) -> impl Fn() + 'a {
move || { console::log(self.value) }
}
fn attach(&self) {
document.add_event_listener("click", self.gen_callback());
}
}
impl Drop for Apple {
// idk how to drop it
// maybe
// document.remove_event_listener("click", self.gen_callback());
// remove from js heap
}
@csharad indeed I hope to do that! My current thinking is that it'll look something like:
let x = Handle::new(|| ...); // create a JS callback
some_js_api(&x); // pass a JS callback (requires `&x`, not `x`-by-value)
drop(x); // invalidates the JS callback and destroys Rust data
That way you'd have to keep it alive in Rust to ensure it's still invoke-able. It could be passed to JS mutliple times to call addEventListener and removeEventListener I believe
Alright! This is now implemented with https://github.com/rustwasm/wasm-bindgen/pull/101 and the various caveats are also documented
Most helpful comment
That's definitely the plan yeah!
I'm starting to work on this now and I'll keep this issue updated with progress