There is some puzzling behaviour when working with dynamicaly created observeEvents for also dynamically created actionsButtons in a DT::dataTableOutput
Have a look at the following app:
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel = sidebarPanel(
textInput("txt","Txt"),
),
mainPanel = mainPanel(
DT::dataTableOutput("dt")
)
)
)
server <- function(input, output, session) {
observeEvent(input$txt, {
output$dt <- DT::renderDT(
data.frame("content" = rep(input$txt, 5),
"buttons" = unlist(lapply(1:5, function(i){
as.character(
actionButton(paste0("ab",i),
label = paste0("ab",i),
onclick = "Shiny.setInputValue(this.id, 42, {priority: 'event'})"
)
)
}))),
escape = FALSE
)
})
abObserver <- function(i, message=" is greeting you"){
print(paste("observeEvent is being created:", i))
observeEvent(input[[paste0("ab",i)]],{
print(paste0("observing ab",i," with message: ",message,"~~~~~~~~",input$txt))
})
}
observerlist <- lapply(1:5, abObserver, message = input$txt)
}
shinyApp(ui, server, options = list('launch.browser'=TRUE))
I have a dataTable with actionButtons. They have their own observeEvents: They print the value of input$txt
at time of creation of the observeEvent (the message-part of the print) and the input$txt
like it is at the time of clicking.
Now please proceed as follows:
- start the app. You will see in the R-console that all observeEvents are created.
- enter "qqq" to
txt
- press
ab1
- you will see the output "observing ab1 with message: qqq~~~~~~~~qqq". So far so good.
- change
txt
to "qqqttt" - now press
ab2
- you will see the output "observing ab2 with message: qqq~~~~~~~~qqqttt"
But at the neither at the time when the observeEvent for ab2
was created nor at the time it was used the first time the input$txt
was "qqq". So I am a bit surprised.
Regarding this whole setup I have a few questions:
- Why do I have to add the
onclick = "Shiny.setInputValue(this.id, 42, {priority: 'event'})"
? I mean, if I press the button, I press the button so why do I have to tell Shiny again that just pressed the button? The observeEvent is already there, so I do not understand why it is not triggered without the onclick-parameter. - When I change the
txt
then all buttons are rendered again. But somehowinput$ab1
is not set back to zero (I saw that using a browser and also that only already pressed buttons are notNULL
). How are the buttons working? - Is this a usual way to include buttons in your datatable?