动态绑定到唯一observeEvent的actionButtons

时间:2015-12-08 13:53:51

标签: r shiny

我想生成动态数量的actionButtons,然后让每个生成的按钮将其编号打印到控制台。这是我迄今为止最好的尝试,但我仍然无法获得前10个按钮中的每个按钮的observeEvent来识别按钮点击。如何将按钮绑定到observeEvent?

library(shiny)

ui <- basicPage(
  fluidRow(
    actionButton(inputId = "add_button",
                 label = "Add Button")
    ),
  uiOutput("more_buttons")
)

server <- function(input, output){

  rvs <- reactiveValues(buttons = list(actionButton(inputId = "button1",
                                               label = 1)))

  observeEvent(eventExpr = input$add_button,
               handlerExpr = {
                 len <- length(rvs$buttons) + 1
                 rvs$buttons[[len]] <- actionButton(inputId = paste0("button",len),
                                             label = len)
               })

  output$more_buttons <- renderUI({
    do.call(fluidRow, rvs$buttons)
  })

  # This is the part that doesn't work
  for(ii in 1:10){
    observeEvent(eventExpr = input[[paste0("button",ii)]],
                 handlerExpr = print(ii))
  }

}

shinyApp(ui, server)

2 个答案:

答案 0 :(得分:4)

你真的很接近,只需将observeEvent部分包裹在本地。

library(shiny)

ui <- basicPage(
  fluidRow(
    actionButton(inputId = "add_button",
                 label = "Add Button")
  ),
  uiOutput("more_buttons")
)

server <- function(input, output){

  rvs      <- reactiveValues(buttons = list(actionButton(inputId = "button1",
                                                    label = 1)))

  observeEvent(eventExpr = input$add_button,
               handlerExpr = {
                 len      <- length(rvs$buttons) + 1
                 rvs$buttons[[len]] <- actionButton(inputId = paste0("button",len),
                                                    label = len)
               })

  output$more_buttons <- renderUI({
    do.call(fluidRow, rvs$buttons)
  })

  observeEvent(rvs$buttons,{
    for(ii in 1:length(rvs$buttons)){
      local({
        i <- ii
        observeEvent(eventExpr = input[[paste0("button",i)]],
                     handlerExpr = {print(sprintf("You clicked btn number %d",i))})
      })
    }
  })

}

shinyApp(ui, server)

答案 1 :(得分:0)

首先,您希望操作按钮具有某种与其输入ID相关联的命名模式。例如。 “ button1”,“ button2”,“ button3”。看起来像您在做什么。

由于输入可以作为列表传递给observeEvent触发器,因此请使用lapply根据您的inputId模式生成输入列表:

 observeEvent(
    lapply(
      names(input)[grep("button[0-9]+",names(input)]),
         function(name) {
            input[[name]]
          }
    ),
    {
      code to run when any button is pressed
    }
  )