R Shiny key input binding

前端 未结 4 2063
旧时难觅i
旧时难觅i 2020-11-27 15:25

In a Shiny application, is it possible to have a binding that listens to what key a user presses down?

I\'m not too familiar with JavaScript, but I\'m looking for s

4条回答
  •  执念已碎
    2020-11-27 16:10

    If you want this to work for multiple presses, you can create an additional press counter that updates on a key press, bind that value to a different variable, and watch the counter rather than the key code. Here's some example UI code:

      tags$script('
        pressedKeyCount = 0;
        $(document).on("keydown", function (e) {
           Shiny.onInputChange("pressedKey", pressedKeyCount++);
           Shiny.onInputChange("pressedKeyId", e.which);
        });'
      )
    

    And associated server code:

      observeEvent(input$pressedKey, {
        if(input$pressedKeyId >= 49 && input$pressedKeyId <= 57){ # numbers
          values$numClick <- (input$pressedKeyId - 48);
          flipNumber();
        }
        if(input$pressedKeyId >= 37 && input$pressedKeyId <= 40){ # arrow keys
          arrowCode <- input$pressedKeyId - 37;
          xInc <- ((arrowCode+1) %% 2) * (arrowCode - 1);
          yInc <- ((arrowCode) %% 2) * (arrowCode - 2) * -1;
          if(!any(values$click == c(-1,-1))){
            values$click <- (((values$click - 1) + c(xInc, yInc) + 9) %% 9) + 1;
          }
        }
      });
    

提交回复
热议问题