Home > Software engineering >  Best way to implement `addValueChangeListener` for a complex Vaadin Component?
Best way to implement `addValueChangeListener` for a complex Vaadin Component?

Time:12-07

I have a rather complex Vaadin component with seven different inputs:

public class MyComponent extends VerticalLayout
    implements HasValue<ValueChangeEvent<MyPojo>, MyPojo> {

  private final ComboBox<String> _objectId = new ComboBox<>();
  private final TextField _accountId = new TextField();
  private final TextField _personId = new TextField();
  private final DatePicker _startDate = new DatePicker();
  private final DatePicker _endDate = new DatePicker();
  private final IntegerField _age = new IntegerField();
  private final NumberField _amount = new NumberField();

  private final Binder<MyPojo> _binder = new Binder<>();

  // more implementation ...
}

Because of the implemented interface I also need to implement Registration addValueChangeListener(ValueChangeListener<? super ValueChangeEvent<MyPojo>> listener) What is the best way to implement this? Is there some automation or do I need to do this by hand, e.g. linking my basic input fields method addValueChangeListener to the complex ValueChangeListener<? super ValueChangeEvent<MyPojo>>? Or could I somehow use the _binder for that?

CodePudding user response:

Yes you chan use a single lister on the binder. I'm in a similar situation and in order to avoid to declare a plethora of listeners, one for each binded field, I just registered on on the binder. There are two events registrations availabel on the binder. One for any of binded field changed, and the other that triggers for a bunch of situation. Here the javadoc: https://vaadin.com/api/platform/21.0.8/com/vaadin/flow/data/binder/Binder.html

CodePudding user response:

Rather than directly implementing the HasValue interface, I would recommend one of the abstract classes that help you with all the nitty gritty details.

In your case, that might be either AbstractCompositeField if you want to have full control over the visual representation or CustomField if you Vaadin to handle things like an input label.

  • Related