gpt4 book ai didi

R Shiny 销毁观察事件

转载 作者:行者123 更新时间:2023-12-01 16:03:11 25 4
gpt4 key购买 nike

我是 R Shiny 的新手。我正在尝试创建一个带有一些动态生成的按钮的应用程序。每个按钮都有一个与之关联的observeEvent。我想添加一个重置按钮来删除所有observeEvents。我浏览了一些链接,发现 destroy() 函数可以用于相同的用途,但我无法弄清楚如何使用它。有什么建议么?谢谢。

library(shiny)
ui<-fluidPage(
actionButton(inputId = "add",label = "Add Stuff"),
htmlOutput("obs"),
actionButton("reset","Reset")
)
server<-function(input,output,session){

output$obs<-renderUI(HTML({names(input)}))

observeEvent(input$add,{
addModal<-function(failed=FALSE){

modalDialog(size = "l",easyClose = T,title = "Add",footer = "",
selectInput(inputId = "stuff",label = "Select",choices = c("A","B","C","D","E")),
numericInput(inputId = "numstuff",label = "Quantity",min = 1,max = 5,value = 1),
actionButton(inputId = "add2",label = "Add")
)

}
showModal(addModal())
})

num<<-0
observeEvent(input$add2,{
num<<-num+1
insertUI(selector = "#add",where = "beforeBegin",
ui = actionButton(inputId = paste0("comp",num),label = paste0(input$stuff,":",input$numstuff))
)
lapply(num:num,function(i){
observeEvent(input[[paste0("comp",i)]],{
modModal<-function(failed=FALSE){

modalDialog(size = "l",easyClose = T,title = "Delete",footer = "",
# numericInput(inputId = "newquan",label = "New Quantity",min=1,max=5,value=1),
actionButton(inputId = paste0("gomod",i),label = "Delete")
)
}
showModal(modModal())
},ignoreInit = T)

observeEvent(input[[paste0("gomod",i)]],{
nm<-paste0("#comp",i)
removeUI(selector=nm)
})

})
})

observeEvent(input$reset,{
observers<-names(input)
lapply(observers,function(x){
if(substr(x,1,4)=="comp"){
obs<-input[[x]]
obs$destroy()
}
})
})

}
shinyApp(ui=ui,server=server)

最佳答案

您必须将observe(或observeEvent)分配给一个变量(例如o),然后调用o$destroy 在观察者体内。 See this app一个使用这个的很好的例子(尽管用例,即在 Shiny 中创建“并发的、 fork 的、可取消的任务”,可能比你的复杂得多)。无论如何,您都可以在那里看到正在运行的机制。

您可能还对 this app 感兴趣,我认为这可以以更简单的方式实现您想要的目标(使用 once = TRUE 参数)。

关于R Shiny 销毁观察事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44367004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com