observeEvent

当某个事件发生时,observeEvent 对象可用于触发一段代码。它构造如下:

observeEvent( event {
code to run
})

observeEvent 只依赖于上面一小段代码中的 event 部分。它不会依赖于运行代码部分中的任何内容。下面是一个示例实现:

library(shiny)

ui <- fluidPage(
  headerPanel("Example reactive"),
  
  mainPanel(
    
    # action buttons
    actionButton("button1","Button 1"),
    actionButton("button2","Button 2")
  )
)

server <- function(input, output) {
  
  # observe button 1 press.
  observeEvent(input$button1, {
    # The observeEvent takes no dependency on button 2, even though we refer to the input in the following line.
    input$button2  
    showModal(modalDialog(
      title = "Button pressed",
      "You pressed one of the buttons!"
    ))
  })
}

shinyApp(ui = ui, server = server)