弹出模式中闪亮的模块化输入在关闭时不会写入 reactiveValues [flexdashboard/shinydashboard]

Shiny modularized inputs inside pop-up modal aren't being written to reactiveValues when dismissed [flexdashboard/shinydashboard]

作为一个最小可行的例子,我 modularized the basic example from here: https://rmarkdown.rstudio.com/flexdashboard/shiny.html#simple_example

代码片段(复制粘贴,运行 作为 RStudio 中的 .Rmd 应该可以做到这一点):

---
title: "Whosebug example"
output: flexdashboard::flex_dashboard
runtime: shiny
---

```{r global, include=FALSE}
library(shiny)
library(flexdashboard)  # install.packages("flexdashboard")
# load data in 'global' chunk so it can be shared by all users of the dashboard
library(datasets)
data(faithful)

# UI modules
sidebarCharts <- function(id) {
  ns <- NS(id)
  tagList(
    p(),
    actionButton(ns("settings"), "Settings", icon = icon("cogs"), width = '100%', class = "btn btn-info"),p(),
    actionButton(ns("refreshMainChart") ,"Refresh", icon("refresh"), width = '100%', class = "btn btn-primary"),p()
    ,textOutput(ns("info"))  # FOR DEBUGGING
  )
}

mainChartUI <- function(id) {
  ns <- NS(id)
  plotOutput(ns("mainChart"), width = "100%")
}

# UI module for the 2 buttons in the modal:
modalFooterUI <- function(id) {
  ns <- NS(id)
  tagList(
    modalButton("Cancel", icon("remove")),
    actionButton(ns("modalApply"), "Apply", icon = icon("check"))
  )
}

server <- function(input, output, session) {

  # Init reactiveValues() to store values & debug info; https://github.com/rstudio/shiny/issues/1588
  rv <- reactiveValues(clicks = 0, applyClicks = 0,
                       bins = 20,
                       bandwidth = 1)

  # DEBUGGING
  output$info <- renderText({
    paste("You clicked the 'Settings' button", rv$clicks, "times. You clicked the 'Apply' button", rv$applyClicks, "times. The bin size is currently set to", rv$bins, "and the bandwidth is currently set to", rv$bandwidth)
  })

  settngsModal <- function(id) {
    ns <- NS(id)
    modalDialog(
      withTags({  # UI elements for the modal go in here
        fluidRow(
          column(4, "Inputs",
                 selectInput(ns("n_breaks"), label = "Number of bins:", choices = c(10, 20, 35, 50), selected = rv$bins, width = '100%')),
          column(4, "Go",
                 sliderInput(ns("bw_adjust"), label = "Bandwidth adjustment:", min = 0.2, max = 2, value = rv$bandwidth, step = 0.2, width = '100%')),
          column(4, "Here")
        )
      }),
    title = "Settings",
    footer = modalFooterUI("inputs"), 
    size = "l",
    easyClose = FALSE,
    fade = TRUE)
  }

  # Sidebar 'Settings' modal
  observeEvent(input$settings, {
    showModal(settngsModal("inputs"))  # This opens the modal; settngsModal() defined below
    rv$clicks <- rv$clicks + 1  # FOR DEBUGGING
  })

  observeEvent(input$modalApply, {
    rv$applyClicks <- rv$applyClicks + 1  # FOR DEBUGGING
    rv$bins <- input$n_breaks  # This is where I set the reactiveValues() to those inputted into the modal.
    rv$bandwith <- input$bw_adjust
    removeModal()  # This should dismiss the modal (but it doesn't seem to work)
  })

  output$mainChart <- renderPlot({
    input$refreshMainChart  # Take dependency on the 'Refresh' buton

    hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(rv$bins),  
         xlab = "Duration (minutes)", main = "Geyser Eruption Duration")

    dens <- density(faithful$eruptions, adjust = rv$bandwidth)
    lines(dens, col = "blue")
  })

}

```

Column {.sidebar}
-----------------------------------------------------------------------

```{r}
callModule(server, "main")
sidebarCharts("main")
```

Column
-----------------------------------------------------------------------

### Main chart goes here

```{r}
mainChartUI("main")
```

截图:

这是所需的功能:

  1. 在应用程序启动时,图表应使用存储在 rv 中的 bin 大小和带宽的默认参数呈现,这是 reactiveValues() -- 这似乎有效。
  2. 当我第一次单击模式时,它应该会出现默认的 bin-size 和 bandwidth 参数 -- 这似乎也有效。
  3. 当我更新任一输入参数 AND 单击 'Apply' 时,它应该关闭模态并随后在 rv reactiveValues() 反对所选的人 -- 这不起作用(模态既没有解除,也没有更新 reactiveValues)。
  4. rv 中的 reactiveValues() 更新为新的之后,图表不应重新呈现,直到用户点击 'Refresh' actionButton -- 这也是不起作用,但取决于上面的 (3)。

我做错了什么??感觉好像忽略了一些超级简单的东西。

谢谢!!

问题是因为您的模式和服务器功能具有不同的 namespace ID,因此无法以正常方式相互通信。

当您使用 callModule 调用 server 函数时,您为模块提供了 "main" 的命名空间 ID。当你生成你的 Modal 时,你给它命名空间 ID "inputs"。因此,当您尝试使用 observeEvent(input$modalApply... 访问服务器中的 actionButton 时,它不起作用,因为它正在其自己的命名空间的 inputs$ 中寻找 modalApply"main"),不存在。

您需要做的是将模态保持在与调用它的服务器函数相同的名称空间中。您可以通过将 ns 函数直接传递到会话中的模态 UI 函数来实现。

不用传入一个id,然后用ns <- NS(id)重新生成ns,你可以直接用session$ns获取当前会话ns函数,然后通过它进入 UI 函数供其使用:

observeEvent(input$settings, {
    showModal(settngsModal(session$ns))
}

...

settngsModal <- function(ns) {
    ...
    footer = modalFooterUI(ns), 
    ...
}

通过以这种方式传递 session$ns,您可以确保模式的 UI 元素将始终与调用它的服务器函数位于相同的命名空间中(因此可访问) .您可以在此处阅读更多相关信息:http://shiny.rstudio.com/articles/modules.html#using-renderui-within-modules


至于你的第二个问题,只需将 renderPlot 中的其余代码包装在 isolate 函数中即可。 isolate 函数使得 isolatereactive 值的变化不会使表达式无效并导致它重新计算。现在,唯一可以导致 renderPlot 重新计算的 reactive 值是 isolate 之外的值:input$refreshMainChart:

output$mainChart <- renderPlot({
    input$refreshMainChart  # Take dependency on the 'Refresh' buton
    isolate({
        hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(rv$bins),  
             xlab = "Duration (minutes)", main = "Geyser Eruption Duration")

        dens <- density(faithful$eruptions, adjust = rv$bandwidth)
        lines(dens, col = "blue")
    })
})