Providing a closure as member of a parameter object to pass to an JS function #3885
Replies: 3 comments 3 replies
-
#[wasm_bindgen]
pub struct ModalConfig {
/// Title of the modal.
title: String,
/// Handler.
handler: Closure<dyn Fn(bool)>,
} The fields are not accesible from JS. These need to be public, but |
Beta Was this translation helpful? Give feedback.
-
The issue is that the fields are private. I was wrong about the hook, the library calling the closure could be catching errors, or it could be reported to another window in the console.
It would probably be easier to first test the bindings independently of the library.
|
Beta Was this translation helpful? Give feedback.
-
I think something like the following will probably work /// [Modal] configuration options.
#[wasm_bindgen]
pub struct ModalConfig {
/// Title of the modal.
pub title: String,
handler: Closure<dyn Fn(bool) -> JsValue>,
}
impl ModalConfig {
/// New modal configuration.
pub fn new<H: Fn(bool) + 'static>(title: &str, handler: H) -> Self {
let handler = Closure::new(handler);
Self {
title: title.to_string(),
handler
}
}
}
#[wasm_bindgen]
extern "C" {
/// A modal.
pub type Modal;
/// Internal function to create the modal on JavaScript side.
#[wasm_bindgen(js_namespace=["$"], js_name="modal")]
fn new_modal_with_config(props: &str, config: ModalConfig) -> Modal;
}
#[wasm_bindgen]
impl ModalConfig {
#[wasm_bindgen]
pub fn handler(&self, v: bool) -> JsValue {
self.handler(v)
}
}
If you find stuff becoming too complex, I don't necessarily think this is a bad idea. There's also the option to use bindings that set a closure on a JsValue. This would be something like the following #[wasm_bindgen]
extern "C" {
#[wasm_bindgen(method, setter)]
fn handler(this: &Modal, f: &mut dyn FnMut());
}
I just meant that you should create bindings, then use those bindings from the console of the browser to test if they work. Attempting to test on bindings for an external JS dependency seems too complicated. |
Beta Was this translation helpful? Give feedback.
-
Summary
Dear Community,
I want to create bindings for the Modal module of fomantic-ui.
The following example is shown for a
confirm
modal in the documentation:The configuration object contains a handler callback.
How is it possible to create a binding for this? As far as I know, there is no method using
serde
for this because a closure is required.I tried:
In my leptos component, I am using:
The code compiles, the modal opens, but there is neither a title, nor does the callback fire when I hit the "OK" button.
Can someone help me to make this work? What I am doing wrong?
Thanks in advance, best regards,
Lewin
Beta Was this translation helpful? Give feedback.
All reactions