使观察事件在闪亮的

时间:2021-07-06 06:36:20

标签: r shiny

有没有办法让观察事件在闪亮的情况下具有反应性?例如,在下面的应用程序中,当用户单击按钮时,应在控制台中打印特定的行号。这只是一个示例应用程序:

library(shiny)
library(shinydashboard)
library(DT)
library(glue)
library(dplyr)
number_compare <- data.frame(replicate(2, sample(1:100, 10, rep=TRUE)))


sidebar <- dashboardSidebar()

body <- dashboardBody(
  fluidRow(box(width = 12, solidHeader = TRUE,
               uiOutput("rt"),
               DTOutput("example_table"))
  )
)

ui <- dashboardPage(dashboardHeader(title = "Example"),
                    sidebar,
                    body
)


server <- function(input, output) {
  
  
  
  number_compare <- number_compare %>% mutate(rn = row_number(), button = glue::glue(HTML('<button id="button{rn}" type="button" class="btn btn-default action-button">Ask a question</button>')))
  
  output$rt <- renderUI({
    selectInput("Sd","Select",choices = number_compare$X1)
  })
  
  output$example_table <- DT::renderDT({
    
    number_compare <- number_compare %>% filter(X1 %in% input$Sd)
    
    datatable(
      number_compare,
      escape = FALSE
      ,options=list(preDrawCallback=JS(
        'function() {
     Shiny.unbindAll(this.api().table().node());}'),
        drawCallback= JS(
          'function(settings) {
       Shiny.bindAll(this.api().table().node());}')))
  })
  
  # observe({
  #   lapply(1:nrow(df), function(x) {
  #     id <- paste0("button",number_compare['rn'][x,])
  #     observeEvent(input[[id]], {print(x)})
  #   })
  # })

  
}

shinyApp(ui, server)

有没有办法让观察事件在闪亮的情况下具有反应性?例如,在下面的应用程序中,当用户单击按钮时,应在控制台中打印特定的行号。

1 个答案:

答案 0 :(得分:0)

以下内容会在控制台中打印行号。

lapply(1:nrow(number_compare), function(x) {
      observeEvent(input[[paste0("button",number_compare['rn'][x,])]], {print(x)})
})

您不需要将其包装在另一个观察者中。