How to implement callback on typing in textbox with rust druid (not lens, but a method call)?

836 Views Asked by At

I want to call the following method with arguments, either by passing them or from a closure:


fn set_border(&mut self, arg: &str, is_left_border: bool) -> () {
        let val = arg.parse::<f64>();
        match val {
            Ok(float) => { if is_left_border {self.left_border = Some(float)} else {self.right_border = Some(float)}},
            Err(_) => {}
        }
    }

when text is entered to the textbox. I didn't find a way to use lens to access methods, but I'm quite new to rust and decided to ask for advice.

As far as I'm concerned if I can "track" changes of the field and do it that way it will also do.

Thanks in advance.

1

There are 1 best solutions below

0
On BEST ANSWER

You can use a Controller to be called when the TextBox receives a call to its update method and then check whether the data has changed:

use druid::{
    AppLauncher,
    WidgetExt,
    Widget,
    Env,
    UpdateCtx,
    WindowDesc,
    widget::TextBox,
    widget::Controller
};

struct UpdateCallback();

impl Controller<String, TextBox<String>> for UpdateCallback {
    fn update(&mut self, 
        child: &mut TextBox<String>, 
        ctx: &mut UpdateCtx<'_, '_>, 
        old_data: &String, 
        data: &String, 
        env: &Env
    ) {
        if old_data != data {
            // the data has changed, you can call your function here
            println!("{}", data);
        }
        // also inform the child that the data has changed
        child.update(ctx, old_data, data, env)
    }
}

fn build_root_widget() -> impl Widget<String> {
    TextBox::new().controller(UpdateCallback())
}

fn main() {
    AppLauncher::with_window(WindowDesc::new(build_root_widget)).launch("Test".to_string()).unwrap();
}

The relevant part here is the Controller impl for UpdateCallback as well as the call to controller() inside the build_root_widget() function.