0

使用e_textof typeweb_sys::HtmlDivElemente_buttonof 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`
4

1 回答 1

1

From性状的倒数是Into。如果存在. Into<T>_OFrom<O>T

fn buildCbClosure(e : impl Into<web_sys::HtmlElement>) -> Closure<dyn FnMut(web_sys::MouseEvent)> {
    let mut e = e.into(); // `e` is an HtmlElement.
}

现在,任何t可以传递给的HtmlElement::from(t)都可以直接传递给buildCbClosure(t).

于 2020-03-01T15:47:19.910 回答