Passing a JS function from JS to Rust?

Suppose we have a JS function

function foo(x) {
  console.log("Yo, JS side says: ", x);
 }

Now, suppose we want it pass it to Rust. The Rust 'receiver' would be something like:

struct Rust_Part {}
impl Rust_Part {
  pub fn rust_handler(callback: &JsValue) { ... }
}
}

Here's my question. How do we use the 'callback' on the Rust side? I want to do something like:

  callback(&"hello world".into::<JsValue>());

except callback itself is a JsValue, and not a function.

Question: how do we use callback on the Rust side ?

I think you can use js_sys::Reflect::apply, though it's fairly awkward to use directly like that

1 Like

I think a slightly cleaner way is to pass it as a Function in js_sys - Rust but I can't figure out what to specify as the context variable.

I think they're basically the same, and I believe the context is the this value for the function

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.