gpt4 book ai didi

javascript - 调用 p :remoteCommand via a JavaScript function passing a message local to that function to another function through the "oncomplete" handler

转载 作者:行者123 更新时间:2023-11-27 23:54:35 24 4
gpt4 key购买 nike

这个问题纯粹基于this之前提出的问题( courtesy ),但这个问题完全被 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>

假设本地 JavaScript 变量 message里面test()函数被分配一条 JSON 消息,该消息通过 WebSockets channel 异步接收。

notifyAll()函数又必须将通知消息( myMessage 本地于 test() 函数 - 实际上是之前在 test() 函数中接收到的 JSON 消息)发送到另一个 WebSockets channel ,为了简洁起见,在这个问题中完全忽略了该消息。

<小时/>

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

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

.

最佳答案

我没有看到比 passing it as a parameter into the <p:remoteCommand> function 更好的方法并拥有 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 注入(inject)到 JS 函数作用域中它代表 XHR 查询字符串。正则表达式从中提取参数。请注意,正则表达式假定参数永远不会出现在查询字符串的开头,这是正确的,因为它总是以 JSF/PF 特定参数开头,因此可以保持简单(JS 正则表达式对于负向后查找很棘手)。

关于javascript - 调用 p :remoteCommand via a JavaScript function passing a message local to that function to another function through the "oncomplete" handler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32377522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com