wasm-bindgen
wasm-bindgen copied to clipboard
How to create a plain javascript object
Summary
I'd like to create rust binding for something like this:
export namespace Math {
type Vector3 = { "x": number, "y": number, "z": number };
}
So I've add binding like this:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(extends = js_sys::Object, js_namespace = Math, js_name = Vector3, typescript_type = "Math.Vector3")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub type JsVector3;
#[wasm_bindgen(constructor, js_class = Vector3)]
pub fn new() -> JsVector3;
#[wasm_bindgen(method, getter, js_class = Vector3, js_name = x)]
pub fn x(this: &JsVector3) -> f64;
#[wasm_bindgen(method, setter, js_class = Vector3, js_name = x)]
pub fn set_x(this: &JsVector3, value: f64);
// ...
}
The problem is I don't know how to create a new JsVector3 object like {x: 1.0, y: 2.0, z: 3.0} in javascript.
I've tried let vec = JsVector3::new() in rust but it won't run as Vector3 is not an actual class in javascript.
Additional Details
I've found this post but I don't know how to cast JsObject to JsVector either.
The snippet above is for js-import (extern "C"), hence using a javascript class from Rust. In this case Vector3 should be declared in javascript. Maybe export from Rust to javascript rust-export is appropriate instead.