【问题标题】:Have downloadButton work with observeEvent让 downloadButton 与 observeEvent 一起工作
【发布时间】:2018-06-27 23:40:04
【问题描述】:

我想添加功能,一旦用户在我闪亮的应用程序中单击 downloadButton,就会向他们提供反馈(例如,它会向用户提供警报消息或在单击后切换 ui 元素)。本质上,我希望能够让downloadButton 下载一些数据并且表现得像actionButton,以便它响应事件触发器。这可能吗?这就是我设置代码的方式:

ui <- fluidPage(
  useShinyjs(),

  downloadButton("download", "Download some data")
)

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

  observeEvent(input$download, {  # supposed to alert user when button is clicked
    shinyjs::alert("File downloaded!")  # this doesn't work
  })

  output$download <- downloadHandler(  # downloads data
    filename = function() {
      paste(input$dataset, ".csv", sep = "")
    },
    content = function(file) {
      write.csv(mtcars, file, row.names = FALSE)
    }
  )

}

shinyApp(ui = ui, server = server)

这似乎只有在我将 ui 中的 downloadButton 更改为 actionButton 元素时才有效,但这样做会禁用下载输出。

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    这有点小技巧,但您可以让downloadHandler 函数修改一个作为触发观察事件的标志的 reactiveValue:

    # Create reactiveValues object
    #  and set flag to 0 to prevent errors with adding NULL
    rv <- reactiveValues(download_flag = 0)
    
    # Trigger the oberveEvent whenever the value of rv$download_flag changes
    # ignoreInit = TRUE keeps it from being triggered when the value is first set to 0
    observeEvent(rv$download_flag, {
        shinyjs::alert("File downloaded!")
    }, ignoreInit = TRUE)
    
    output$download <- downloadHandler(  # downloads data
        filename = function() {
            paste(input$dataset, ".csv", sep = "")
        },
        content = function(file) {
            write.csv(mtcars, file, row.names = FALSE)
            # When the downloadHandler function runs, increment rv$download_flag
            rv$download_flag <- rv$download_flag + 1
        }
    )
    

    【讨论】:

    • 感谢您的帮助!但奇怪的是,这仍然不会触发observeEvent。但是,我可以通过在 downloadHandler 的 if 语句中嵌套 rv$download_flag 来使其工作
    【解决方案2】:

    根据上面 divibisan 的回答,我可以通过在 downloadHandler 的 if 语句中嵌套 rv$download_flag 来触发事件:

      # Create reactiveValues object
      # and set flag to 0 to prevent errors with adding NULL
      rv <- reactiveValues(download_flag = 0)
    
      output$download <- downloadHandler(  # downloads data
        filename = function() {
          paste(input$dataset, ".csv", sep = "")
        },
        content = function(file) {
          write.csv(mtcars, file, row.names = FALSE)
          # When the downloadHandler function runs, increment rv$download_flag
          rv$download_flag <- rv$download_flag + 1
    
          if(rv$download_flag > 0){  # trigger event whenever the value of rv$download_flag changes
            shinyjs::alert("File downloaded!")
          }
    
        }
      )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-13
      • 2016-10-06
      • 2011-11-30
      • 2014-02-19
      • 2011-09-03
      • 2013-05-01
      • 2018-05-30
      • 2014-03-17
      相关资源
      最近更新 更多