我在我的网络应用中Binding Data to Forms, Checking a return value使用了代码的binder.addStatusChangeListener( ... )
部分。从中得出的MCVE是:
public class Person implements Serializable {
private String name;
public Person() {}
public Person( final String name ) {
this.name = name;
}
public String getName() {
return name;
}
public void setName( final String name ) {
this.name = name;
}
}
public class PersonView extends VerticalLayout {
private final Person person = new Person( "Gerold Broser" );
private final TextField name = new TextField( "Name:" );
private final BeanValidationBinder<Person> binder =
new BeanValidationBinder<>( Person.class );
private final Button button = new Button( "Button" );
public PersonView() {
super();
binder.bindInstanceFields( this );
binder.setBean( person );
addComponent( name );
addComponent( button );
binder.addStatusChangeListener( event -> {
final boolean hasChanges, isValid;
out.println( "hasChanges=" + (hasChanges = event.getBinder().hasChanges()) );
out.println( "isValid=" + (isValid = event.getBinder().isValid()) );
button.setEnabled( hasChanges && isValid );
} );
}
}
只要我在浏览器中更改了TextField
的内容,我就会得到以下输出:
hasChanges=false
isValid=true
这是一个错误还是我错过了什么?
答案 0 :(得分:2)
来自javadoc:
public boolean hasChanges()
检查是否有任何绑定字段&#39;自上次显式调用
readBean(Object)
,removeBean()
,writeBean(Object)
或之后,我们发生了未提交的更改writeBeanIfValid(Object)
。不成功的写入操作不会影响此值。请注意,如果您使用
setBean(Object)
方法,Binder会在所有验证程序通过后立即尝试提交更改。因此,在使用时 这种方法很少有意义,几乎总是回归 假强>每种情况的返回值都编译成如下 表:
╔════════════╦════════════╦═════════╦═════════╦══════════════════╦════════════════════╗
║ ║ After ║ After ║ After ║ After successful ║ After unsuccessful ║
║ ║ readBean, ║ valid ║ invalid ║ writeBean or ║ writeBean or ║
║ ║ setBean or ║ user ║ user ║ writeBeanIfValid ║ writeBeanIfValid ║
║ ║ removeBean ║ changes ║ changes ║ ║ ║
╠════════════╬════════════╬═════════╬═════════╬══════════════════╬════════════════════╣
║ A bean is ║ ║ ║ ║ ║ ║
║ currently ║ false ║ false ║ true ║ false ║ no change ║
║ bound ║ ║ ║ ║ ║ ║
╟────────────╫────────────╫─────────╫─────────╫──────────────────╫────────────────────╢
║ No bean is ║ ║ ║ ║ ║ ║
║ currently ║ false ║ true ║ true ║ false ║ no change ║
║ bound ║ ║ ║ ║ ║ ║
╚════════════╩════════════╩═════════╩═════════╩══════════════════╩════════════════════╝
Returns:
自上次调用setBean,readBean,writeBean或writeBeanIfValid以来是否有任何绑定字段的值发生了变化
总之,使用setBean(myBean)
将触发自动提交。因此,如果您想manually commit changes,请使用binder.readBean(myBean)
&amp; binder.writeBean(myBean)
。