为p:pickList构建客户端传输方法

我正在使用Mojarra JSF 2.1.28和Primefaces 3.5。 我想为p:pickList组件实现客户端传输输入,其中用户键入内容并通过可用元素列表中的标签搜索值,然后将其传输到目标列表。 这就是我的代码的样子:

     //Just for testing, transfer the second element //to the target list when document is ready. Works well $(document).ready(function(string) { transfer("name2"); }); //Transfer function. It takes each list item from the source list and checks if it matches with the given pattern //If it does, moves it to the target list function transfer(string) { $(".ui-picklist-source li").each(function() { var re = new RegExp(string); if ($(this).attr('data-item-label').match(re)) { $(".ui-picklist-target").append($(this)); } }); };   

 @ManagedBean @ViewScoped public class Bean implements Serializable{ public class Element { private String name; public Element(String n) { name = n; } public String getName() { return name; } @Override public String toString() { return "Element [name=" + name + "]"; } } private DualListModel elements; public Bean() { List source = new ArrayList(); List target = new ArrayList(); source.add(new Element("name1")); source.add(new Element("name2")); elements = new DualListModel(source, target); } public DualListModel getElements() { return elements; } public void send() { System.out.println("Available: " + elements.getSource() + " assigned: " + elements.getTarget()); } public void setElements(DualListModel elements) { this.elements = elements; } } 

好吧,在这个测试用例中,有两个项目可以使用, name1name2 。 当页面加载时,我使用$(document).ready()来调用我的transfer(string)函数,以便将name2移动到目标列表。 页面获得正确加载,如果我们单击“ Send按钮,我们会正确分配第二个元素。

使用p:inputText组件调用函数时出现问题。 在这里,我们监听Enter键事件以发送当前给定值并执行传输。 在客户端,它工作得很公平,它的行为符合预期。 但是,单击“ Send ,模型在服务器端无法正确更新。

我推断这是由JSF保存的视图状态引起的,但是如何处理呢? 有没有办法实现它,还是我必须坚持Ajax请求?

实现这一目标的“正确”方法是使用Primefaces的Javascript API

PrimeFaces.widget.PickList

假设你的widgetVarpickListWV ,你可以这样做:

 function transfer(string) { PF('pickListWV').sourceList.children().each(function() { var re = new RegExp(string, "i"); if ($(this).attr('data-item-label').match(re)) { PF('pickListWV').selectItem($(this));// select the item PF('pickListWV').add();// add it to the target } }); } 

编辑:你也可以使它更有趣,如实时过滤..

   

编辑2:

我可以看到你有一个区分大小写的匹配,所以你必须声明你的RegExp不区分大小写

 var re = new RegExp(string, "i"); 

这是github上的一个小工作示例,以及一个按要求运行的演示 🙂

希望这可以帮助。