2015-09-03 124 views
1

這個問題純粹是基於this之前問過的問題(courtesy),但問題與Java完全混淆了EE 7 WebSockets API嘗試顯示實際的方法/場景,現在很難接收基於<p:remoteCommand>的任何答案。通過JavaScript函數調用ap:remoteCommand,通過「oncomplete」處理函數將本地消息傳遞給另一個函數


下面給出了一段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變量messagetest()函數內分配有異步通過的WebSockets信道接收的JSON消息。

反過來notifyAll()函數必須發送通知消息(myMessage本地的test()功能 - 實際上這是在test()功能先前接收的JSON消息)發送到另一個的WebSockets信道,其在這個問題爲了簡潔完全忽略。


是否有可能通過oncomplete處理程序給定<p:remoteCommand>來的var message = "myMessage"本地的test()函數值傳遞給另一個函數notifyAll()

聲明message作爲全局JavaScript變量可能壓倒的WebSockets作爲消息的功能被接收異步即可以接收到新的消息而<p:remoteCommand>處理仍在繼續/等待完成。因此,將message聲明爲全局JavaScript變量不是一種選擇。

回答

1

我看不到比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參數已經在JS功能範圍由oncomplete注入並且它表示XHR查詢字符串。正則表達式從中提取參數。請注意,正則表達式假定參數永遠不在查詢字符串的開頭,因爲它始終以JSF/PF特定參數開頭,所以它可以保持簡單(JS正則表達式比較棘手,帶負向後視)。

+0

'data'從哪裏來?我正在'undefined'。 – Tiny

+0

對不起,我忘了答案中的「」位。 – BalusC

+0

接收'未捕獲的ReferenceError:未定義數據'。生成的腳本如下所示:''。 – Tiny

相關問題