ShinyBS bsPopover和updateSelectInput

时间:2016-05-01 11:08:03

标签: r shiny shinybs

我想向动态用户界面添加工具提示。 当我初始化UI时,工具提示工作正常

selectInput(ns("Main2_1"),"Label","abc",  selectize = TRUE, multiple = TRUE),
bsPopover(ns("Main2_1"), "Label", "content", placement = "left", trigger = "focus"),

但是一旦我用

更新我的服务器脚本中Main2_1的选项
updateSelectInput(session, "Main2_1", choices=foo)

它也会删除工具提示。在服务器端添加addPopover的新工具提示并不能解决问题

1 个答案:

答案 0 :(得分:1)

我同意,这是一些糟糕的设计。我甚至不能说,为什么addPopover不起作用。也许是因为观察者不会逐个执行命令......

然而,有一种方法可以达到你的目的。通过重写bsPopover,我们可以考虑相应元素的更改。

我创建了一个updateResistantPopover函数,它为元素添加了一个额外的eventListener(mutationListener),只要给出了id,就会在元素的某个子元素发生变化时重新安装popover。

以下示例代码:

library(shiny)
library(shinyBS)

updateResistantPopover <- function(id, title, content, placement = "bottom", trigger = "hover", options = NULL){
  options = shinyBS:::buildTooltipOrPopoverOptionsList(title, placement, trigger, options, content)
  options = paste0("{'", paste(names(options), options, sep = "': '", collapse = "', '"), "'}") 
  bsTag <- shiny::tags$script(shiny::HTML(paste0("
    $(document).ready(function() {
      var target = document.querySelector('#", id, "');
      var observer = new MutationObserver(function(mutations) {
        setTimeout(function() {
          shinyBS.addTooltip('", id, "', 'popover', ", options, ");
        }, 200);
      });
      observer.observe(target, { childList: true });
    });
  ")))
  htmltools::attachDependencies(bsTag, shinyBS:::shinyBSDep)
}

ui <- shinyUI(fluidPage(
  selectInput("Main2_1","Label","abc",  selectize = TRUE, multiple = TRUE),
  updateResistantPopover("Main2_1", "Label", "content", placement = "right", trigger = "focus"),
  actionButton("destroy", "destroy!")    
))

server <- function(input, output, session){     
  observeEvent(input$destroy, {
    updateSelectInput(session, "Main2_1", choices="foo")
  })
}

shinyApp(ui, server)