observeEvent 监听任何具有相同名称模式的输入

observeEvent listen to any input with same name pattern

我有一个闪亮的应用程序,其中包含许多具有相似 ID 的输入。他们中的任何一个都应该触发一个动作。我需要动态引用 observeEvent 侦听器中的那些输入 ID。输入的数量未知,所以我需要一个通用的解决方案。我试图用正则表达式命名输入,但没能成功。这是一个示例应用程序:

library(shiny)

ui <- fluidPage(
  actionButton("button_1", label = "Button 1"),
  actionButton("button_2", label = "Button 2"),
  actionButton("button_3", label = "Button 3")
)

server <- function(input, output, session) {
  
  observeEvent((input$button_1|input$button_2|input$button_3),  { #Replace with listen to any input with id starting with "button_"
    showModal(modalDialog("Thanks for pushing the button"))
  })
 }

shinyApp(ui, server)

我为您在 observeEvent

eventExpr 中定义的许多按钮做了这项工作
library(shiny)

ui <- fluidPage(
  actionButton("button_1", label = "Button 1"),
  actionButton("button_2", label = "Button 2"),
  actionButton("button_3", label = "Button 3")
)

server <- function(input, output, session) {
  
  observeEvent(
    eventExpr = {
      buttons <- paste0("button_",1:10)
      list_of_buttons = NULL
      for(var in buttons) {
        list_of_buttons <- append(list_of_buttons, input[[var]])
      }
      list_of_buttons
  }, 
    handlerExpr = { #Replace with listen to any input with id starting with "button_"
      showModal(modalDialog("Thanks for pushing the button"))
  }, 
  ignoreInit = T
)}

shinyApp(ui, server)

您可以使用动态数量的按钮

library(shiny)

ui <- fluidPage(
  actionButton("button_1", label = "Button 1"),
  actionButton("button_2", label = "Button 2"),
  actionButton("button_3", label = "Button 3")
)

server <- function(input, output, session) {
  
  observeEvent(
    lapply(
      names(input)[grep("button_[0-9]+",names(input))],
      function(name){input[[name]]}),  {
        showModal(modalDialog("Thanks for pushing the button"))
  }, ignoreInit = TRUE)
  
}

shinyApp(ui, server)