我正在使用下拉列表中的选项动态构建面包屑作为菜单项值,但我遇到了一个奇怪的行为。以下是我正在使用的代码:
breadcrumb.xhtml:
<h:form>
<p:breadCrumb id="breadcrumb" model="#{breadcrumbVO.menuModel}">
</p:breadCrumb>
<p:selectOneMenu id="select-box" value="#{breadcrumbVO.selectedOption}">
<p:ajax listener="#{breadcrumbVO.selectionChanged}" update="@form" />
<f:selectItem itemLabel="- Select -" itemValue="" noSelectionOption="true" />
<f:selectItems value="#{breadcrumbVO.selectItems}" />
</p:selectOneMenu>
</h:form>
BreadcrumbVO.java
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.MenuElement;
import org.primefaces.model.menu.MenuModel;
@ManagedBean
@ViewScoped
public class BreadcrumbVO implements Serializable {
private static final long serialVersionUID = -4419933664561553404L;
private MenuModel menuModel;
private List<SelectItem> selectItems;
private String selectedOption;
public BreadcrumbVO() {
menuModel = new DefaultMenuModel();
DefaultMenuItem menuItem = new DefaultMenuItem();
menuItem.setValue("USA");
menuItem.setCommand("#{breadcrumbVO.onBredcrumbMenuClick()}");
menuItem.setUpdate("@form");
menuModel.addElement(menuItem);
initSelectMenu();
}
public void selectionChanged() {
if(this.selectedOption != ""){
DefaultMenuItem menuItem = new DefaultMenuItem();
menuItem.setValue(this.selectedOption);
menuItem.setCommand("#{breadcrumbVO.onBredcrumbMenuClick()}");
menuItem.setUpdate("@form");
this.menuModel.addElement(menuItem);
refreshSelectMenu();
}
}
private void refreshSelectMenu() {
this.selectedOption = null;
selectItems = new ArrayList<SelectItem>();
selectItems.add(new SelectItem("New Item3", "New Item3"));
selectItems.add(new SelectItem("New Item4", "New Item4"));
}
private void initSelectMenu(){
this.selectItems = new ArrayList<SelectItem>();
selectItems.add(new SelectItem("New Item1", "New Item1"));
selectItems.add(new SelectItem("New Item2", "New Item2"));
}
public void onBredcrumbMenuClick(){
List<MenuElement> menuElements = this.menuModel.getElements();
menuElements.remove(menuElements.size()-1);
initSelectMenu();
}
public List<SelectItem> getSelectItems() {
return selectItems;
}
public void setSelectItems(List<SelectItem> selectItems) {
this.selectItems = selectItems;
}
public MenuModel getMenuModel() {
return menuModel;
}
public void setMenuModel(MenuModel menuModel) {
this.menuModel = menuModel;
}
public String getSelectedOption() {
return selectedOption;
}
public void setSelectedOption(String selectedOption) {
this.selectedOption = selectedOption;
}
}
我观察到的奇怪行为是我在构造函数中添加到menuItem
的{{1}}正常工作并正确调用bean中的方法menuModel
。但是,由于用户从下拉列表中选择了某个值而添加的其他menuItem,不会在单击时调用此方法。即使我对菜单项使用相同的配置,但它们的行为也有所不同,具体取决于它们在onBredcrumbMenuClick
中的添加时间。
感谢您的解释。