You can use shiny's JS event shiny:inputchanged
to check which input changed:
ui <- fluidPage(
tags$head(
tags$script(
"$(document).on('shiny:inputchanged', function(event) {
if (event.name != 'changed') {
Shiny.setInputValue('changed', event.name);
}
});"
)
),
numericInput("a", "a", 0),
textInput("b", "b"),
textInput("c", "c"),
textOutput("changedInputs"),
textOutput("aFired")
)
server <- function(input, output, session) {
output$changedInputs <- renderText({
paste("Outside observer: Latest input fired:", paste(input$changed, collapse = ", "))
})
observeEvent({
c(input$a,
input$b)
}, {
req(input$changed)
if (input$changed == "a") {
output$aFired <- renderText("Inside observer: input$a was fired")
} else if (input$changed == "b") {
output$aFired <- renderText("Inside observer: input$b was fired")
} else if (input$changed == "c") {
output$aFired <- renderText("Inside observer: input$c was fired")
}
}, ignoreInit = TRUE)
}
shinyApp(ui, server)
:
Edit - request from @TristanTran using renderUI
:
library(shiny)
ui <- fluidPage(
tags$head(
tags$script(
"$(document).on('shiny:inputchanged', function(event) {
if (event.name != 'changed') {
Shiny.setInputValue('changed', event.name);
}
});"
)
),
uiOutput("serverside"),
textOutput("changedInputs"),
textOutput("aFired")
)
server <- function(input, output, session) {
output$changedInputs <- renderText({
paste("Outside observer: Latest input fired:", paste(input$changed, collapse = ", "))
})
output$serverside <- renderUI({
tagList(
numericInput("a", "a", 0),
textInput("b", "b"),
textInput("c", "c")
)
})
observeEvent({
c(input$a,
input$b)
}, {
req(input$changed)
if (input$changed == "a") {
output$aFired <- renderText("Inside observer: input$a was fired")
} else if (input$changed == "b") {
output$aFired <- renderText("Inside observer: input$b was fired")
} else if (input$changed == "c") {
output$aFired <- renderText("Inside observer: input$c was fired")
}
}, ignoreInit = TRUE)
}
shinyApp(ui, server)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…