Search code examples
rustwasm-bindgen

How to put a trait bound for web_sys::HtmlElement::from function


With e_text of type web_sys::HtmlDivElement and e_button of type web_sys::HtmlButtonElement this function builds a Closure to a on_click callback. Compiles and runs ok.

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()));

Next step is to generalize and move web_sys::HtmlElement::from into the buildCbClosure function, but haven't found a traitbound on e that captures this. Have tried something like below, and this is obvious a From trait in the wrong direction. The other direction is like an general upcast from different subtypes of 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
}

Gives:

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`

Solution

  • The inverse of the From trait is Into. Into<T> is automatically implemented for a type O, if a From<O> implementation exists for T.

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

    Now, any t that can be passed to HtmlElement::from(t) can be passed directly to buildCbClosure(t).