InputEvent for IntegerField with debounce

Hello,
I’m trying to capture the keyboard input of a IntegerField.

I can get the value with a ValueChangeListener:

integerField.component.addValueChangeListener(e -> {
    Integer newValue = e.getValue();
    answer.textValue = String.valueOf(newValue);
    saveAnswer(answer);
});

This only fires when the input field loses focus.
I would like to have a debounce of 300ms when the keyboard entry stops.

integerField.component.addInputListener(e -> {
    String newValue = e.getSource().getElement().getProperty("value");
    integerField.component.getElement().executeJs(
        "setTimeout(() => { $0.$server.saveAnswer($1); }, 300);",
        integerField.component, newValue
    );
    answer.textValue = newValue;
});

This function correctly fires on input but, the new value is not passed along.

Any suggestions on how I might add an InputListener and get the current input value?
Thank you.

You should be able to use the built-in API for debouncing:

field.setValueChangeMode(ValueChangeMode.LAZY);
field.setValueChangeTimeout(300);

Then just use the value change listener as usual.

1 Like