获取在Shiny中触发的事件?

时间:2019-06-26 10:08:33

标签: r events shiny

我想在下面的示例中知道在多个ObserveEvent()中触发了哪个事件。

ui <- fluidPage(
  numericInput("a", "a", 0),
  textInput("b", "b")
)

server <- function(input, output, session) {
  observeEvent({
    input$a
    input$b
  },{

    # If only input$a is fired, I want to know that is input$a

  })
}

shinyApp(ui, server)

还是唯一的解决方案是像第二个链接一样具有两个ObserveEvent()?这样吗?

ui <- fluidPage(
  numericInput("a", "a", 0),
  textInput("b", "b")
)

server <- function(input, output, session) {
  observeEvent({
    input$a
  },{

    my_function_or_reactive_function(input,1)

  })

  observeEvent({
    input$b
  },{

    my_function_or_reactive_function(input,2)

  })

}

shinyApp(ui, server)

链接:

1 个答案:

答案 0 :(得分:2)

您可以使用闪亮的JS event shiny:inputchanged检查更改了哪个输入:

ui <- fluidPage(
  tags$head(
    tags$script(
      "$(document).on('shiny:inputchanged', function(event) {
          if (event.name != 'changed') {
            Shiny.setInputValue('changed', event.name);
          }
        });"
    )
  ),
  numericInput("a", "a", 0),
  textInput("b", "b"),
  textInput("c", "c"),
  textOutput("changedInputs"),
  textOutput("aFired")
)

server <- function(input, output, session) {
  output$changedInputs <- renderText({
    paste("Outside observer: Latest input fired:", paste(input$changed, collapse = ", "))
  })

  observeEvent({
    c(input$a,
      input$b)
  }, {
    req(input$changed)
    if (input$changed == "a") {
      output$aFired <- renderText("Inside observer: input$a was fired")
    } else if (input$changed == "b") {
      output$aFired <- renderText("Inside observer: input$b was fired")
    } else if (input$changed == "c") {
      output$aFired <- renderText("Inside observer: input$c was fired")
    }
  }, ignoreInit = TRUE)
}

shinyApp(ui, server)

Result