Using API Helpers for Defining Component Properties

The framework provides a helper called PropertyDescriptor which makes managing attributes and properties in a component easy. You can use PropertyDescriptor to define the property name and the default value in a single place and use the descriptor from the setter and getter methods:

Java

  1. @Tag("input")
  2. public class TextField extends Component {
  3. private static PropertyDescriptor<String, String> VALUE =
  4. PropertyDescriptors.propertyWithDefault("value", "");
  5. public String getValue() {
  6. return get(VALUE);
  7. }
  8. public void setValue(String value) {
  9. set(VALUE, value);
  10. }
  11. }

In your component API for a given property, e.g. value of an input field, you want to ensure a couple of things are always true:

  • The getter and setter use the same property or attribute

  • The default value is handled properly

  • The getter return value is either the type used by the setter, e.g. String for an input value or an optional version of it, i.e. Optional<String> if the property is not mandatory.

PropertyDescriptors will automatically take these points into consideration for you.

PropertyDescriptor instances are created using the helpers available in the PropertyDescriptors class. There are different helper methods depending on how you want your property to work:

  • PropertyDescriptors.propertyWithDefault for mapping to an element property with a given default value

  • PropertyDescriptors.attributeWithDefault for mapping to an element attribute with a given default value

  • PropertyDescriptors.optionalAttributeWithDefault for mapping to an element attribute with a given default value but returning an empty Optional when the default value is set

You can use the optionalAttributeWithDefault e.g. for a placeholder in a TextField as the placeholder is not mandatory:

Java

  1. @Tag("input")
  2. public class TextField extends Component {
  3. private static PropertyDescriptor<String, Optional<String>> PLACEHOLDER =
  4. PropertyDescriptors.optionalAttributeWithDefault("placeholder", "");
  5. public Optional<String> getPlaceholder() {
  6. return get(PLACEHOLDER);
  7. }
  8. public void setPlaceholder(String placeholder) {
  9. set(PLACEHOLDER, placeholder);
  10. }
  11. }
Note
The default value used in the PropertyDescriptors methods should match what the value becomes in the browser when the attribute or property is not set. Otherwise the value will not be correctly sent to the browser when the user sets the value to the default value.