Home:ALL Converter>How to call an arbitrary previously defined javascript function Rust using wasm-bindgen?

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

Ask Time:2020-07-16T21:14:30         Author:Claudio Soprano

Json Formatter

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

Author:Claudio Soprano,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/62935592/how-to-call-an-arbitrary-previously-defined-javascript-function-rust-using-wasm
yy