rustrust-wasm

Rust Wasm attach input event listener to element


How do I add an input event listener to an HtmlInputElement/HtmlTextAreaElement?

I'm using web-sys and read this, but following that, all the elements I use inside the closure (in this case especially the input element) get moved into the closure and I can't attach the listener afterwards.

let closure = Closure::wrap(Box::new(|_: web_sys::InputEvent| {
    console_log!("{}", input.value());
}) as Box<dyn FnMut(_)>);

input.add_event_listener_with_callback("input", closure.as_ref().unchecked_ref())?;
// ^
// Doesn't work because the `input` variable was moved into the closure.

Concretely speaking, I get:

borrow of moved value: `input`

Solution

  • First of all, I would like to thank Svetlin Zarev for taking the time to answer my question. I wouldn't have come to this without them. And please check out their answer.

    For someone coming from javascript, all this stuff is quite a lot to take in and I wanted to present a "simple" answer.

    To add an input (or really any kind) of event listener and capture the targets value, you may use the following code:

    let cb = Closure::wrap(Box::new(|e: Event| {
        let input = e
            .current_target()
            .unwrap()
            .dyn_into::<web_sys::HtmlTextAreaElement>()
            .unwrap();
    
        console_log!("{:?}", input.value());
    }) as Box<dyn FnMut(_)>);
    
    input.add_event_listener_with_callback("input", &cb.as_ref().unchecked_ref())?;
    
    cb.forget();
    

    I would also recommend reading the following articles: