1

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?

2
  • 2
    Are you not familiar with JavaScript coding practices? There's nothing special about this code from the JS point of view, which is kind of the point. Commented Jun 28, 2018 at 15:43
  • I am making a DSL in Rust to create React components. They are created using JavaScript functions: function Hello(props) { return <h1>Hello!</h1>;} is a component that can be used as var elem = <Hello/>;. When I create the component in Rust and use it in the same file I need to add the namespace. From another file, I can do import { Hello } from './comp.js'; and use Hello without a namespace. I want to use Hello without a namespace in both cases. Commented Jun 28, 2018 at 23:01

1 Answer 1

1

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}, ...);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.