我有一个带有一些文本字段的基本BeanFieldGroup
编辑器。我公开了save - Button
,以便Presenter
个类可以注册到它。
问题:当视图中的TextField
元素有验证错误时,我想阻止clickevent的传播(因为无效的输入值需要进一步的用户输入,不应该触发任何其他操作)。
但我该如何预防呢?
class UserView {
private TextField username = new TextField("username");
private Button save;
private BeanFieldGroup<User> editor;
public UserView() {
editor = new BeanFieldGroup<User>(User.class);
save = new Button("Save", new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
try {
editor.commit();
} catch (CommitException e) {
//how can I prevent the click event to be routed to the presenter?
Notification.show("Form invalid");
}
}
});
}
public getSaveBtn() {
return save;
}
}
class UserPresenter implements Button.ClickListener {
void bind() {
view.getSaveBtn().addClickListener(this);
}
@Override
public void buttonClick(ClickEvent event) {
//this should be prevented if username field has validation errors in view
doa.save(entity);
}
}
答案 0 :(得分:1)
您的代码没问题,只是您为保存按钮注册了两个ClickListeners
。演示者中的监听器有效地绕过了editor
FieldGroup的验证逻辑,因为无论FieldGroup的验证结果如何,都会调用它。您需要的是演示者上的一种方法,只有在成功验证输入后才会调用该方法。
因此,UserView
中ClickListener的代码应如下所示:
save = new Button("Save", new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
try {
editor.commit();
// no CommitException thrown until now, so go ahead and tell the presenter:
presenter.doSave(entity);
} catch (CommitException e) {
// validation failed -> don't tell the presenter
Notification.show("Form invalid");
}
}
});