R闪亮销毁ObserveEvent

Ayu*_*ush 3 r shiny

我是R Shiny的新手。我正在尝试使用一些动态生成的按钮来创建一个应用程序。每个按钮都有一个与之关联的observeEvent。我想添加一个重置按钮,该按钮将删除所有observeEvent。我浏览了一些链接,发现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)
Run Code Online (Sandbox Code Playgroud)

小智 7

您必须将observe(或observeEvent)分配给变量(例如o),然后o$destroy在观察者的体内调用。请参阅此应用程序,以获取使用它的一个很好的示例(尽管用例在“ Shiny”中创建“并行,分叉,可取消的任务”,可能比您的复杂得多)。无论如何,您都可以在那里看到该机制的作用。

您可能对此应用程序也很感兴趣,我认为该应用程序可以更轻松地实现您想要的功能(使用once = TRUE参数)。