调用f:ajax keydown事件但仅在按下左箭头键时

时间:2014-07-07 15:05:13

标签: jsf primefaces

有没有好处,所以以下事件只调用左箭头上的ajax请求,否则正常行动。

<h:selectOneMenu id="menuId" value="#{bean.value}" converter="entityConverter">
        <f:selectItem noSelectionOption="true" itemLabel="All Categories"/>
        <f:selectItems  value="#{bean.valueList" var="value" 
            itemLabel="#{value.subcatName}" itemValue="#{value}"/>
            <f:ajax event="keydown"
                    listener="#{bean.goBack()}"
                    execute="@this"                                 
                    render="@form"
                    onevent="function(data) { if (data.status === 'begin') { //is there something I can do here?}}"/>
</h:selectOneMenu>

1 个答案:

答案 0 :(得分:3)

当您似乎使用Primefaces时,请利用其p:remoteCommand实用程序。它创建了一个javascript函数,可用于生成ajax请求。对于你的情况,它可能是:

@ManagedBean
@ViewScoped
public class SelectionBean implements Serializable {

    private List<String> values = Arrays.asList("val1", "val2");

    private String selection;

    public String getSelection() {
        return selection;
    }

    public void setSelection(String selection) {
        this.selection = selection;
    }

    public List<String> getValues() {
        return values;
    }

    public void goBack() {
        System.out.println("Going back...");
    }

}
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">

<h:head />

<h:body>

    <h:form>
        <p:remoteCommand name="goBack"
            actionListener="#{selectionBean.goBack}" />
        <script>
            function processKey(e) {
                if (e.keyCode == 37) {
                    goBack();
                }
            }
        </script>
        <h:selectOneMenu value="#{selectionBean.selection}"
            onkeydown="processKey(event);">
            <f:selectItems value="#{selectionBean.values}" />
        </h:selectOneMenu>
    </h:form>

</h:body>
</html>

这里我们使用辅助JS函数来检查事件keyCode是否是左箭头的函数。如果为true,则调用Primefaces生成的JS函数,该函数将触发服务器端方法。

相关问题