使用 Rust 和wasm-bindgen
.
用 构建元素document.create_element(tag)
,它返回一个web_sys::Element
。元素被转换为特定类型,具体取决于标签,例如web_sys::HtmlButtonElement
. 这可行,并且还放入了一个小包装器,用于设置元素类型特定的构建器。
struct ElemSpec<T> {
html_tag : html_const::HtmlTag<'static>,
resource_type: std::marker::PhantomData<T>
}
impl<T : wasm_bindgen::JsCast> ElemSpec<T> {
fn build_element(&self) -> T {
let window = web_sys::window().expect("no global `window` exists");
let document = window.document().expect("should have a document on window");
let elem = document.create_element(&self.html_tag);
let elem = match elem {
Ok(e) => e,
Err(error) => {
panic!("Call to document.create_element failed with error: {:?}", error)
},
};
let result = wasm_bindgen::JsCast::dyn_into::<T>(elem);
let helement = match result {
Ok(e) => e,
Err(e) => {
panic!("Cast to specific Element failed tag:{}", &self.html_tag);
},
};
helement
}
}
const BUTTON_ELEM : ElemSpec<web_sys::HtmlButtonElement> =
ElemSpec{ html_tag: html_const::BUTTON, resource_type: std::marker::PhantomData};
这是有效的,一个HtmlButtonElement
是用:
let buttonElement = BUTTON_ELEM.build_element();
现在我寻找一个特征 Bound,它限制为可以从web_sys::Element
. 例如HtmlSpanElement
, HtmlDivElement
, ..., HtmlButtonElement
。
附加或替换 Bound to wasm_bindgen::JsCast
in impl<T : wasm_bindgen::JsCast>
,可以这样做吗?