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)