使用e_text
of typeweb_sys::HtmlDivElement
和e_button
of typeweb_sys::HtmlButtonElement
这个函数构建一个 on_click 回调的闭包。编译运行正常。
let a = buildCbClosure(web_sys::HtmlElement::from(e_text));
fn buildCbClosure(mut e : web_sys::HtmlElement) -> Closure<dyn FnMut(web_sys::MouseEvent)> {
let a = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {
handleButtonClick(&event);
e.set_text_content(Some("Text - Klik"));
}) as Box<dyn FnMut(_)>);
a
}
e_button.set_onclick(Some(a.as_ref().unchecked_ref()));
下一步是泛化并web_sys::HtmlElement::from
进入buildCbClosure
函数,但还没有找到e
捕捉到这一点的 traitbound。尝试过类似下面的方法,这显然是一个From
错误方向的特征。另一个方向就像来自 的不同子类型的一般向上转换web_sys::HtmlElement
:
fn buildCbClosure<T : From<web_sys::HtmlElement>>(mut t : T) -> Closure<dyn FnMut(web_sys::MouseEvent)> {
let mut elem = web_sys::HtmlElement::from(t);
let a = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {
handleButtonClick(&event);
elem.set_text_content(Some("Text - Klik"));
}) as Box<dyn FnMut(_)>);
a
}
给出:
error[E0277]: the trait bound `web_sys::HtmlElement: std::convert::From<T>` is not satisfied
--> src/lib.rs:59:20
|
59 | let mut elem = web_sys::HtmlElement::from(t);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::convert::From<T>` is not implemented for `web_sys::HtmlElement`