Reputation: 43
I'm using wasm bindgen and I have following function :
#[wasm_bindgen]
pub fn obj(o: &JsValue){
console::log_1(o);
}
and in js I call this function obj({name: "john"});
and it works fine, but when i try to console::log_1(o.name);
it gives error unknown field
pointing at name
Upvotes: 3
Views: 3402
Reputation: 2128
There is a third variant: Use js_sys::Reflect::get
.
In your case it would look like this:
let value = js_sys::Reflect::get(o, &"name".into())?;
console::log_1(value);
Please check the wasm_bindgen docs for Accessing Properties of Untyped JavaScript Values.
Upvotes: 3
Reputation: 2942
JsValue
does not have a field name
. To get this field you have to declare the JS object.
Variant 1
Add serde to your dependencies:
serde = "^1.0.101"
serde_derive = "^1.0.101"
Rust code:
extern crate serde;
#[derive(Serialize, Deserialize)]
pub struct User {
pub name: String,
}
#[wasm_bindgen]
pub fn obj(o: &JsValue){
let user: User = o.into_serde().unwrap();
console::log_1(user.name);
}
Variant 2
Another way is to use wasm-bindgen directly but I never used it. It should work like this I think:
#[wasm_bindgen]
pub struct User {
pub name: String,
}
#[wasm_bindgen]
pub fn obj(o: User){
console::log_1(o.name);
}
Upvotes: 5