Claudio Soprano
Claudio Soprano

Reputation: 51

How to call an arbitrary previously defined javascript function Rust using wasm-bindgen?

In my javascript, before calling wasm, I define a function jalert that I later want to call from Rust using wasm. I couldn't find in the documentation for wasm-bindgen how to call an arbitrary function that I previously defined in javascript as below. I got functions like alert and console.log to work, because they are already part of javascript, but I couldn't have this function jalert to work. I get an error in the browser, saying that it is not defined. With the alert function, it doesn't complain.

    function jalert(sometext) {
        alert(sometext);
    }
    
    jalert("I am Claudio");
    
    // This works from Javascript

In the Rust file lib.rs:

    #[wasm_bindgen]
    extern "C" {
        fn alert(s: &str);
        fn jalert(s: &str);
    }
    
    #[wasm_bindgen]
    pub fn run_alert(item: &str) {
        jalert(&format!("This is WASM calling javascript function jalert and {}", item));
        alert(&format!("This is WASM and {}", item));
    }
    
// The alert() code works fine. The jalert() call in run_alert() gives me a browser error that jalert is not defined

Upvotes: 5

Views: 995

Answers (1)

Michael
Michael

Reputation: 2942

I'd say you need to add #wasm_bindgen to your method declaration:

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(method, js_name = alert]
    fn alert(s: &str);
    #[wasm_bindgen(method, js_name = jalert]
    fn jalert(s: &str);
}

Upvotes: 0

Related Questions