如何查看由renderUI生成的闪亮仪表板框是否折叠?

问题描述 投票:0回答:1

我的 R 闪亮应用程序中有由 renderUI/uiOutput 生成的(不同)数量的可折叠框,我想看看它们是否从服务器折叠。当在 ui here 中定义框时,有一个关于如何执行此操作的问题和答案,但是当我在服务器功能内创建框时,这不起作用。然而,以编程方式折叠它们仍然可以正常工作。这就是现在的样子:

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

jscode <- "
shinyjs.collapse = function(boxid) {
$('#' + boxid).closest('.box').find('[data-widget=collapse]').click();
}
"
collapseInput <- function(inputId, boxId) {
  tags$script(
    sprintf(
      "$('#%s').closest('.box').on('hidden.bs.collapse', function () {Shiny.onInputChange('%s', true);})",
      boxId, inputId
    ),
    sprintf(
      "$('#%s').closest('.box').on('shown.bs.collapse', function () {Shiny.onInputChange('%s', false);})",
      boxId, inputId
    )
  )
}

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    useShinyjs(),
    extendShinyjs(text = jscode, functions = c("collapse")),
    actionButton("bt1", "Collapse box1"),
    actionButton("bt2", "Collapse box2"),
    br(), br(),
    # This is where the boxes were defined in the original question & answer
    # box(id = "box1", collapsible = TRUE, p("Box 1")),
    # box(id = "box2", collapsible = TRUE, p("Box 2")),
    uiOutput("boxes"), # This does not exist in the original
    collapseInput(inputId = "iscollapsebox1", boxId = "box1"),
    verbatimTextOutput(outputId = "res")
  )
)

server <- function(input, output) {
  output$boxes <- renderUI({ # This does not exist in the original
    do.call(tagList, 
            list(box(id = "box1", collapsible = TRUE, p("Box 1")),
            box(id = "box2", collapsible = TRUE, p("Box 2")))
            )
  })
  observeEvent(input$bt1, {
    js$collapse("box1")
  })
  observeEvent(input$bt2, {
    js$collapse("box2")
  })
  
  output$res <- renderPrint({
    input$iscollapsebox1
  })
}

shinyApp(ui, server) 

我对 javascript 的经验很少,所以我不太确定这里会发生什么。我尝试将调用移至崩溃输入(),但这似乎没有改变任何东西。

r shiny shinydashboard
1个回答
0
投票

你的盒子最初并不存在,所以

$("#box1")
什么也没找到。如果您将脚本包含在
renderUI
中,则可以:

  output$boxes <- renderUI({ 
    do.call(tagList, 
            list(
              box(id = "box1", collapsible = TRUE, p("Box 1")),
              box(id = "box2", collapsible = TRUE, p("Box 2")),
              collapseInput(inputId = "iscollapsebox1", boxId = "box1")
            )
    )
  })
© www.soinside.com 2019 - 2024. All rights reserved.