我想添加一些功能,一旦用户在我闪亮的应用程序中单击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
元素时才起作用,但是这样做会禁用下载输出。
答案 0 :(得分:1)
这有点麻烦,但是您可以让downloadHandler
函数修改reactactValue,该行为充当触发观察事件的标志:
# 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
}
)
答案 1 :(得分:0)
基于上面divibisan的回答,我能够通过将rv$download_flag
嵌套在downloadHandler
的if语句中来触发事件:
# 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!")
}
}
)