Shiny: Feature requested: Get the event which is fired in ObserveEvent

Created on 27 Jun 2019  路  2Comments  路  Source: rstudio/shiny

Hello,

From my question below in stackoverflow I was surprised that the functionality of getting the event which is fired in ObserveEvent() apparently doesn't exist by default in observeEvent().

I've looked for "event fired" in the issues and the Shiny docs but I didn't found it :)

Have a good day.

Here is the copy-paste of the stackoverflow workaround by ismirsehregal

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

  p("changedInputs:"), textOutput("changedInputs"), br(),
  p("aFired:"), textOutput("aFired")
)

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

  myText <- reactiveVal()

  observeEvent(eventExpr = {
    lapply(grep(pattern = "^a_+[[:digit:]]$|^c$", x = isolate({names(input)}), value = TRUE), function(x){input[[x]]})
  }, handlerExpr = {
    req(input$changed)
    if (input$changed == "a_1") {
      myText("Inside observer: input$a_1 was fired")
    } else  if (input$changed == "a_2") {
      myText("Inside observer: input$a_2 was fired")
    } else {
      myText(paste("Inside observer:", input$changed, "was fired"))
    }
  }, ignoreInit = TRUE)

  output$aFired <- renderText({myText()})

}

shinyApp(ui, server)
Advanced Medium Low Type

Most helpful comment

All 2 comments

Here is a simplified example showing the mentioned workaround (based on the JS event shiny:inputchanged) to receive the input names which triggered observeEvent(). The SO example might be a little difficult to get into.

library(shiny)

ui <- fluidPage(
  tags$head(
    tags$script(
      "$(document).on('shiny:inputchanged', function(event) {
          if (event.name != 'changed') {
            Shiny.setInputValue('changed', event.name);
          }
        });"
    )
  ),
  sliderInput("a", "input$a", 0, 10, 5),
  sliderInput("b", "input$b", 0, 10, 5),
  sliderInput("c", "input$c", 0, 10, 5),
  textOutput("printChangedInputs"),
  textOutput("printTrigger")
)

server <- function(input, output, session) {
  observeEventTrigger <-  reactiveVal()

  observeEvent(c(input$a, input$b), {
    observeEventTrigger(req(input$changed))
    cat("My execution was triggered by input:", observeEventTrigger(), "\n")
  }, ignoreInit = TRUE)

  output$printChangedInputs <- renderText({
    paste("Latest input used:", input$changed)
  })

  output$printTrigger <- renderText({
    paste("Latest observeEvent trigger:", observeEventTrigger())
  })
}

shinyApp(ui, server)
Was this page helpful?
0 / 5 - 0 ratings