通过JavaScript函数调用p:remoteCommand,通过"oncomplete"将该函数

Invoking a p:remoteCommand via a JavaScript function passing a message local to that function to another function through the "oncomplete" handler

本文关键字:quot 通过 函数 oncomplete JavaScript 函数调用 remoteCommand      更新时间:2023-09-26

这个问题纯粹是基于之前问过的问题(礼貌),但是这个问题完全被Java EE 7 WebSockets API弄乱了,它试图展示实际的实用方法/场景,现在不太可能收到任何基于<p:remoteCommand>的答案。


下面给出一段JavaScript代码(这只是一个测试场景):

<script type="text/javascript">
    function test() {
        var message = "myMessage";
        window["myFunction"]();
        // This is literally interpreted as a JavaScript function "myFunction()".
        // "myFunction()" in turn is associated with a <p:remoteCommand>.
    }
    $(document).ready(test);
    function notifyAll() {
        alert("notifyAll() invoked.");
    }
</script>

test()函数在页面加载后立即调用,导致以下<p:remoteCommand>触发,进而调用另一个JavaScript函数,即notifyAll(),使用oncomplete处理程序简单地提醒上述消息。

<h:form>
    <p:remoteCommand process="@this"
                     name="myFunction"
                     actionListener="#{bean.listener}"
                     oncomplete="notifyAll()"
                     ignoreAutoUpdate="true"/>
</h:form>

假设test()函数中的本地JavaScript变量message被分配了一个JSON消息,该消息通过WebSockets通道异步接收。

notifyAll()函数反过来必须向另一个WebSockets通道发送通知消息(myMessage本地test()函数-实际上是之前在test()函数中收到的JSON消息),该通道在此问题中被完全忽略。


是否有可能通过给定<p:remoteCommand>oncomplete处理程序将var message = "myMessage"的值传递给test()函数的另一个函数notifyAll() ?

message声明为全局JavaScript变量可能会压倒WebSockets的功能,因为消息是异步接收的即,当<p:remoteCommand>的处理仍在进行/等待完成时,可能会收到新消息。因此,不能将message声明为全局JavaScript变量。

.

我没有看到比将其作为参数传递到<p:remoteCommand>函数并从中提取oncomplete函数更好的方法。

function test() {
    var message = "myMessage";
    myFunction([{name: "message", value: message}]);
}
function notifyAll(data) {
    var message = decodeURIComponent(data.match(/&message=([^&]*)/)[1]);
    // ...
}
<p:remoteCommand name="myFunction" ... oncomplete="notifyAll(this.data)" />

data参数已经被oncomplete注入到JS函数作用域中,它代表XHR查询字符串。正则表达式从中提取参数。注意,regex假设参数永远不会出现在查询字符串的开头,这是真的,因为它总是以JSF/PF特定的参数开始,所以它可以保持简单(JS regex在反向查找方面很棘手)。

相关文章: