我有一个带有一些文本字段的基本 BeanFieldGroup
编辑器。我公开了 save-Button
以便 Presenter
类可以注册到它。
问题:当 View 中的 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);
}
}
最佳答案
您的代码很好,只是您为保存按钮注册了两个 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");
}
}
});
关于java - 如果字段存在验证错误,如何防止 ClickEvent 传播?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23754174/