首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R闪亮:从模块外部使用update*

R闪亮:从模块外部使用update*
EN

Stack Overflow用户
提问于 2018-02-23 08:59:27
回答 1查看 1.1K关注 0票数 2

在不重复callModule()调用或参数的情况下,从一个闪亮模块外部使用update*的最佳方法是什么?

最起码的例子:

代码语言:javascript
复制
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)

默认情况下,“坏更新”将重写原始文本。更好的更新通过重新传递原始文本来避免这种情况,但这并不理想,因为:

  1. 它至少需要两个callModule()调用。
  2. 您必须重复callModule()参数。

理想情况下,一个callModule()调用将负责指定模块参数和更新行为。不过,我还没有找到或想出一种方法来做这件事。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-23 15:13:17

您可以使用reactiveValues()来完成这个任务。您只需要确保考虑到传递给模块的参数的反应性:

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48944330

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档