Data-Centric Applications with Vaadin 8
上QQ阅读APP看书,第一时间看更新

Data binding

Data binding is typically done through the Binder class. This class allows you to connect the values in one or more fields to Java properties in a domain class. Suppose you have a User class (the domain class) with a password Java String as one of its properties. You can create a TextField and bind its value to the password property as follows:

TextField textField = new TextField(“Email”);
Binder binder = new Binder<User>()
.forField(textField)
.bind(User::getPassword, User::setPassword);

This is a powerful and type-safe way of implementing data binding. Imagine that you, at some point during development, decide to rename the password property in the User class to something like pin. You can use the refactoring tools of your IDE to rename the property, and the IDE will rename the getters, setters, and any code calling these two methods. Of course, you'd have to change the caption "Email" to "PIN" yourself, but that would have also been the case with other binding mechanisms.

Binders are also used to add validators and converters. These can be added using Lambda expressions or method references. For example, the following snippet of code checks that a String has exactly 4 characters and converts it into an integer:

binder.withValidator(s -> s.length() == 4, “Must be 4 characters")
.withConverter(Integer::parseInt, Object::toString);