2016-10-11 24 views
0

我正在使用ShinyJavaScript。我將Shiny的功能擴展爲JavaScript。這樣做,我與callbackHandlers工作。 我觀察到在JS中實現的click event的用戶輸入。一旦事件被解僱,我將所需的數據發送到R,其中一項功能與數據一起工作。結果再次返回到JS,其中處理數據的顯示。已添加「...」類型消息的未捕獲處理程序已添加

所以。在我JS身邊,我有這樣的事情:

for(var i = 0; i < radioButtons.length; i++) { 
    radioButtons[i].onclick = function() { 
     if (parseInt(this.value) === 10) { 
      Shiny.onInputChange("go", this.value); 
      Shiny.addCustomMessageHandler("someCallbackHandler1", function(someJson) { 
       someFunction(someJson); 
      }); 

     } else if (parseInt(this.value) === 11) { 
      Shiny.onInputChange("go", this.value); 
      Shiny.addCustomMessageHandler("someCallbackHandler2", function(someJson) { 
       someFunction(someJson); 
      }); 
     } // more else if checking for the value 
     .... 

R方面我做這個

observe({ 
if(!is.null(input$go)) { 
    if((input$go == 10)) { 
     sendToJs1[["myJson"]] <- someFunctionIwrote(arg1, arg2, arg3, arg4) 
     session$sendCustomMessage(type = "someCallbackHandler1", sendToJs1$myJson) 

    } else if((input$go == 11)) { 
     sendToJs2[["myJson"]] <- someFunctionIwrote(arg1, arg2, arg3, arg4, arg5, arg6) 
     session$sendCustomMessage(type = "someCallbackHandler2", sendToJs2$myJson) 

    } # more else if checking for which value gets send from js 
    .... 

當我點擊radioButton與價值10,然後在radioButton與價值11然後再次在radioButton與值10我得到這個。

類型「someCallbackHandler1」的消息,未捕獲的處理程序已經添加

所以JScallbackHandler1已添加,不會再添加它的通知。但我需要再次添加它才能顯示數據。另外,如果輸入數據改變並且someFunctionIwrote(arg1, arg2, arg3, arg4)以不同的輸入數據執行,JS會執行什麼操作?當然callbackHandler1已經加了,不過裏面的,結果從R發到JS是不一樣的。

我該如何處理這種情況?

回答

1

我的建議是:

  1. 定義你的JavaScript事件處理程序只有一次,你的循環之外。不需要多次定義它們。一旦創建完成,他們將不斷收聽來自服務器的消息。

  2. 確保處理程序中聲明的回調函數足夠靈活以處理所有服務器響應。所以你的功能someFunction()應該能夠處理來自服務器的所有可能的消息。

因此,代碼是:

// function to be called from inside the callback functions: 
function someFunction(someJson){ 
console.log("No matter what someJson is, I will handle them all properly!"); 
... 
} 

// set the event handlers for message from server: 
Shiny.addCustomMessageHandler("someCallbackHandler1", function(someJson) { 
       someFunction(someJson); 
      }); 
Shiny.addCustomMessageHandler("someCallbackHandler2", function(someJson) { 
       someFunction(someJson); 
      }); 

// set the event handlers for radio button clicks: 
for(var i = 0; i < radioButtons.length; i++) { 
    radioButtons[i].onclick = function() { 
     if (parseInt(this.value) === 10) { 
      Shiny.onInputChange("go", this.value); 
     } else if (parseInt(this.value) === 11) { 
      Shiny.onInputChange("go", this.value); 
     } // more else if checking for the value 
+0

哦,非常感謝!這樣可行。將'Shiny.addCustomMessageHandler'放在循環外部工作!我想知道爲什麼,你能澄清一下嗎? – Stophface

+0

當您創建已經創建的事件偵聽器時,Shiny將不會接受該事件。我不知道確切的原因;但這是他們的工作方式。 – nilsole

+0

好的。謝了哥們! – Stophface

相關問題