Skip to content

Get back struct returned by a JS Function js_sys::Function #1642

Open
@gawen

Description

@gawen

Given a js_sys::Function which is a JS closure returning an instance of an exported Rust struct SomeObject, how can I get back the returned instance ?

Rust:

#[wasm_bindgen] 
pub struct SomeObject {}

#[wasm_bindgen] 
impl SomeObject {
    #[wasm_bindgen(constructor)]
    pub fn new() -> SomeObject {
        SomeObject {}
    }
}

#[wasm_bindgen] 
pub fn do_call(f: js_sys::Function) -> Result<(), JsValue> {
    // f returns an instance of SomeObject
    let ret: JsValue = f.call0(&JsValue::NULL)?;

    // XXX how to try_cast ret to its original SomeObject?

    // do something with SomeObject's instance

    Ok(())
}

JS:

wasm.do_call(function() {
    return new wasm.SomeObject();
});

I read the related issue #1509 and quoting #1509 (comment) :

[...] the only way currently to unwrap it is to call a by-value-self method on the JS object itself, which will do the unwrapping. [...]

However I don't know how to apply it in this situation.

I'm newbie therefore I may have missed something. Do you have any suggestions?

Thanks,
Gawen

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedWe could use some help fixing this issue!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions