在 JSF 2 的 AjaxBehaviorEvent 中捕获 KeyCode [英] Catch KeyCode in AjaxBehaviorEvent of JSF 2

查看:16
本文介绍了在 JSF 2 的 AjaxBehaviorEvent 中捕获 KeyCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JSF ajax keyup 事件链接到支持 bean 中的事件监听器.

I have a JSF ajax keyup event linked to an event listner in a backing bean.

JSF 文件中的代码如下所示.

The code in the JSF file is like below.

<h:inputText id="txtDescription" value="#{institutionController.current.description}" disabled="#{institutionController.modifyControlDisable}" >
    <f:ajax event="keyup" listener="#{institutionController.changeDetailsEvent}" />
</h:inputText>

支持 bean 中的代码如下所示.

The code in the backing bean is like below.

public void changeDetailsEvent(AjaxBehaviorEvent event) {
}

我想根据按键实现不同的逻辑,如下所示的伪代码.

I want to achieve different logic depending on the key presses, like shown is pseudocode below.

public void changeDetailsEvent(AjaxBehaviorEvent event) {
    If (event.key = Key.enter) {
        do something;
    } else if (event.key = Key.Escape) {
        so something else;
    } else {
        do nothing;
    }

}

谁能告诉我这是如何在支持 bean 中完成的?

Can someone please tell me how this is done in the backing bean?

推荐答案

AjaxBehaviorEvent 不包含任何关于 JavaScript event 对象的信息.您需要自己传递所需的信息.这可以通过一个隐藏的输入字段来实现,该字段的值将由 JavaScript 预填充.例如,

The AjaxBehaviorEvent doesn't contain any information about the JavaScript event object. You need to pass the desired information along yourself. This can be achieved by a hidden input field whose value is to be prefilled by JavaScript. For example,

<h:inputText value="#{bean.input}" onkeyup="document.getElementById('#{keyCode.clientId}').value=event.keyCode">
    <f:ajax event="keyup" execute="@this keyCode" listener="#{bean.listener}" />
</h:inputText>
<h:inputHidden id="keyCode" binding="#{keyCode}" value="#{bean.keyCode}" />

(请注意隐藏字段的id包含在execute中,以便在ajax请求中提交,还请注意binding 用于在document.getElementById()中动态获取生成的客户端ID以设置键码值,也可以硬编码客户端ID如果它是固定的)

(please note that the id of the hidden field is included in execute so that it get submitted along on the ajax request, please also note that the binding is used to be able to dynamically obtain the generated client ID in document.getElementById() in order to set the key code value, you could alternatively also hardcode the client ID if it's fixed)

private String input;
private int keyCode;

public void listener() {
    switch (keyCode) {
        case 13:
            // Enter key was pressed.
            break;
        case 27:
            // Escape key was pressed.
            break;
        default:
            // Other key was pressed.
            break;
    }
}

您可以在 Mozilla DOM 参考.

You can find an overview of all valid keyCode values in the Mozilla DOM reference.

这篇关于在 JSF 2 的 AjaxBehaviorEvent 中捕获 KeyCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆