英文:
Vaadin : preventing MenuBar from closing when MenuBarRootItem is clicked
问题
我使用Vaadin 24。我有一个MenuBar,并且我想修改MenuBar的默认行为,使其在单击项目时不会关闭(以便能够多次单击它们)。有人知道如何实现这一点吗?
这是我的代码:
MenuBar menu = new MenuBar();
menu.addItem(VaadinIcon.PLUS.create(), event -> increase());
menu.addItem(VaadinIcon.MINUS.create(), event -> decrease());
英文:
I am using vaadin 24. I have a MenuBar and I would like to modify the default behavior of MenuBar so that it doesn't close when I click on the items (to be able to click them several times). Do someone know how to achieve this please ?
Here's my code :
MenuBar menu = new MenuBar();
menu.addItem(VaadinIcon.PLUS.create(), event -> increase());
menu.addItem(VaadinIcon.MINUS.create(), event -> decrease());
答案1
得分: 1
这是一个已知的遗漏1。以下是来自问题单的解决方法:
/*
* 当单击菜单项时,不要关闭包含该菜单项的覆盖层({@link SubMenu})。
*/
public class RetainOpenedMenuItemDecorator {
public static final String CHECKED_ATTR = "menu-item-checked";
private final MenuItem menuItem;
public RetainOpenedMenuItemDecorator(MenuItem menuItem) {
this.menuItem = menuItem;
menuItem.getElement().addEventListener("click", e -> {
if (!menuItem.isCheckable()) {
return;
}
// 需要这个操作,因为也阻止了 UI 更改
if (menuItem.isChecked()) {
menuItem.getElement().executeJs("this.setAttribute('" + CHECKED_ATTR + "', '')");
} else {
menuItem.getElement().executeJs("this.removeAttribute('" + CHECKED_ATTR + "')");
}
}).addEventData("event.preventDefault()");
}
public MenuItem getMenuItem() {
return menuItem;
}
public static void keepOpenOnClick(MenuItem menuItem) {
new RetainOpenedMenuItemDecorator(menuItem);
}
public static void keepOpenOnClick(SubMenu subMenu) {
subMenu.getItems().forEach(RetainOpenedMenuItemDecorator::keepOpenOnClick);
}
}
英文:
It's a known omission. Here's a workaround from the ticket:
/*
* Do not close the overlay ({@link SubMenu} containing this menu item when clicked.
*/
public class RetainOpenedMenuItemDecorator {
public static final String CHECKED_ATTR = "menu-item-checked";
private final MenuItem menuItem;
public RetainOpenedMenuItemDecorator(MenuItem menuItem) {
this.menuItem = menuItem;
menuItem.getElement().addEventListener("click", e -> {
if (!menuItem.isCheckable()) {
return;
}
// needed because UI change is also prevented
if (menuItem.isChecked()) {
menuItem.getElement().executeJs("this.setAttribute('"+ CHECKED_ATTR + "', '')");
} else {
menuItem.getElement().executeJs("this.removeAttribute('"+ CHECKED_ATTR + "')");
}
}).addEventData("event.preventDefault()");
}
public MenuItem getMenuItem() {
return menuItem;
}
public static void keepOpenOnClick(MenuItem menuItem) {
new RetainOpenedMenuItemDecorator(menuItem);
}
public static void keepOpenOnClick(SubMenu subMenu) {
subMenu.getItems().forEach(RetainOpenedMenuItemDecorator::keepOpenOnClick);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论