下面的代码示例生成简单的 shinyApp,其中包含数字输入和数据表,其中包含行中的按钮。数据表中的行数与数字输入相同。此外,每个按钮都会被观察并在按下时生成警报。
library(shiny)
library(DT)
library(shinyjs)
exampleModuleUI <- function(id) {
ns <- NS(id)
DT::DTOutput(ns("table"))
}
exampleModule <- function(input, output, session, max.index) {
ns <- session$ns
output$table <- renderDataTable(
data.frame(
buttons = unlist(
lapply(
1:max.index,
function(index) {
as.character(
actionButton(
ns(as.character(index)),
as.character(index)
)
)
}
)
)
),
escape = FALSE,
style = 'bootstrap',
extensions = 'FixedColumns',
options = list(
preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
)
)
lapply(
1:max.index,
function(index) {
observeEvent(input[[as.character(index)]], {
shinyjs::alert(as.character(index))
})
}
)
}
ui <- fixedPage(
useShinyjs(),
numericInput(
"count",
"Count of button in table",
value = 3,
min = 3,
max = 7,
step = 1
),
exampleModuleUI("dt.table")
)
server <- function(input, output, session) {
max.count <- reactive({
input$count
})
observeEvent(
max.count(), {
callModule(exampleModule, "dt.table", max.count())
}
)
}
shinyApp(ui, server)
问题
如果在数字输入中首先输入例如“7”,然后输入“6”,然后再输入“7”,将不再观察到任何按钮。当您再次调用某个模块时,似乎出了点问题,但我不清楚具体原因。但最有趣的问题是“如何让它发挥作用? ”