【问题标题】:R Shiny Destroy ObserveEventR Shiny Destroy ObserveEvent
【发布时间】:2017-11-06 02:42:08
【问题描述】:

我是 R Shiny 的新手。我正在尝试使用一些动态生成的按钮创建一个应用程序。每个按钮都有一个与之关联的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)

【问题讨论】:

  • Here你可以找到相关答案。

标签: r shiny


【解决方案1】:

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

您可能还对this app 感兴趣,我认为它可以更轻松地完成您想要的工作(使用once = TRUE 参数)。

【讨论】:

  • 在这里查看示例会有所帮助
猜你喜欢
  • 2022-01-19
  • 2018-12-05
  • 2018-12-14
  • 2019-08-01
  • 2021-11-14
  • 2017-02-23
  • 2018-11-18
  • 2021-06-06
  • 2021-12-21
相关资源
最近更新 更多