在不重复callModule()调用或参数的情况下,从一个闪亮模块外部使用update*的最佳方法是什么?
最起码的例子:
library(shiny)
numericInputModUI <- function (id) {
ns <- NS(id)
tagList(
numericInput(ns("val"), "Value", value = 0),
textOutput(ns("text"))
)
}
numericInputMod <- function (input, output, session,
updateVal = NA, displayText = "default text") {
output$text <- renderText(displayText)
if (!is.na(updateVal)) updateNumericInput(session, "val", value = updateVal)
}
ui = fluidPage(
numericInputModUI("module"),
actionButton("updateBad", label = "Bad Update"),
actionButton("updateBetter", label = "Better Update")
)
server = function(input, output, session) {
callModule(numericInputMod, "module", displayText = "original text")
observeEvent(
input$updateBad,
callModule(numericInputMod, "module", updateVal = 1)
)
observeEvent(
input$updateBetter,
callModule(numericInputMod, "module", updateVal = 2, displayText = "original text")
)
}
shinyApp(ui, server)默认情况下,“坏更新”将重写原始文本。更好的更新通过重新传递原始文本来避免这种情况,但这并不理想,因为:
理想情况下,一个callModule()调用将负责指定模块参数和更新行为。不过,我还没有找到或想出一种方法来做这件事。
发布于 2018-02-23 15:13:17
您可以使用reactiveValues()来完成这个任务。您只需要确保考虑到传递给模块的参数的反应性:
library(shiny)
numericInputModUI <- function (id) {
ns <- NS(id)
tagList(
numericInput(ns("val"), "Value", value = 0),
textOutput(ns("text"))
)
}
numericInputMod <- function (input, output, session, updateVal = NA,
displayText = "default text", trig) {
output$text <- renderText(displayText())
observeEvent(trig(), ignoreInit = TRUE, {
updateNumericInput(session, "val", value = updateVal())
})
}
ui = fluidPage(
numericInputModUI("module"),
actionButton("updateBad", label = "Bad Update"),
actionButton("updateBetter", label = "Better Update")
)
server = function(input, output, session) {
vals <- reactiveValues(dText = "original text", uVal = NA, trig = 0)
observeEvent(input$updateBad, {
vals$dText <- "default text"
vals$uVal <- 1
vals$trig <- vals$trig + 1
})
observeEvent(input$updateBetter, {
vals$dText <- "original text"
vals$uVal <- 2
vals$trig <- vals$trig + 1
})
callModule(numericInputMod, "module",
displayText = reactive(vals$dText),
updateVal = reactive(vals$uVal),
trig = reactive(vals$trig))
}
shinyApp(ui, server)https://stackoverflow.com/questions/48944330
复制相似问题