dilvan
dilvan

Reputation: 2239

How to call a Rust function from JavaScript without a namespace?

I am using the stdweb library to call a Rust function from JavaScript:

#[js_export]
fn handleClick(e: Value) {
    js!{ alert("Hello!"); }
}

It works, but I have to add the namespace Module.exports. to call it:

React.createElement("p",{onClick: e => Module.exports.handleClick(e) }, ... }

How can I hide this namespace or make it smaller?

Upvotes: 1

Views: 1041

Answers (1)

dilvan
dilvan

Reputation: 2239

I couldn't call a Rust function by name from JavaScript unless I exported it first (#[js_export]). However, the js! macro from the stdweb library allows JavaScript code to call a regular Rust function:

fn handleClick(e: Value) {
    js!{ alert("Hello!"); }
}

To call it:

js!{
    React.createElement("p",{onClick: @{handleClick} }, ...);
}

or, if you really need to name the function:

js!{
    const fct = @{handleClick};
    React.createElement("p",{onClick: fct}, ...);

Upvotes: 1

Related Questions