验证Shiny模块中的可选反应堆

时间:2018-08-02 08:53:21

标签: r shiny

背景

shiny中开发模块时,我有时需要可选参数。我通常将默认值设置为NULL,在相关的观察者中,我使用NULL测试req(my_reactive)的情况。然后,我还想测试reactive是否也是truthy,所以我需要另一个req(my_reactive())

问题

重复的req()构造有点过头了。是否有另一种方法为可选的reactives提供默认设置?


示例

library(shiny)
library(shinydashboard)
library(shinyjs)
library(glue)

mybox_ui <- function(id) {
  ns = NS(id)
  tagList(
    useShinyjs(),
    div(
      box(title = id, 
          solidHeader = TRUE,
          width = 4,
          status = "info"),
      id = ns("box-parent")
    )
  )
}

mybox <- function(input, output, session, get_width = NULL) {
  ns <- session$ns
  observe({
    req(get_width) # assure get_width != NULL
    req(get_width()) # assure get_width() is truthy
    ## or req(get_width, get_width())
    runjs(code = glue('var $el = $("#{ns("box-parent")} > :first");',
                      '$el.removeClass(function (index, className) {{',
                      'return (className.match(/(^|\\s)col-sm-\\d+/g) || []).join(" ")',
                      '}});',
                      '$el.addClass("col-sm-{get_width()}");'))
  })
}

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(selectInput("cols", NULL, c(2, 3, 4, 6, 12), 4)),
  dashboardBody(
    mybox_ui("dynamic_box"),
    mybox_ui("static_box")
  )) 

server <- function(input, output) {
  callModule(mybox, "dynamic_box", reactive(input$cols))
  callModule(mybox, "static_box")

}

shinyApp(ui, server)

0 个答案:

没有答案