繁体   English   中英

R Shiny Destroy ObserveEvent

[英]R Shiny Destroy ObserveEvent

我是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 请参阅此应用程序以获得使用它的一个很好的例子(虽然用例,即在Shiny中创建“并发,分叉,可取消的任务”,可能比你的更复杂)。 无论如何,你可以看到那里的机制。

您可能也对这个应用程序感兴趣,我认为它可以更简单地完成您想要的任务(使用once = TRUE参数)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM