R Shiny-更新ShinyTree节点选择

时间:2019-06-12 05:36:33

标签: r shiny shinytree

下面的应用程序包含一个shinyTree,一个重置按钮(Reset nodes)和一个打印输出“选定的节点”。打印输出打印get_selected函数的输出,该函数返回所选节点的列表。

这是启动时树的屏幕截图:

enter image description here

未选择任何节点,因此get_selected返回一个空的list()

当我进行选择时,例如节点aget_selected会正确返回该选择:

enter image description here

当我单击Reset nodes时,将在树UI中清除节点选择,但是get_selected不会与先前的选择保持不变:

enter image description here

单击重置按钮后,观察者将通过updateTree更新树,如下所示:

observeEvent(input$reset, {

    updateTree(session,"tree", data = tree)
  })

我希望get_selected返回list()时会重设。我使用的是updateTree吗?

以下是复制以上代码的代码:

library(shiny)
library(shinyTree)

tree = structure(list(a=list(a1=1,a2=2) , b="b"), stopened = T) 

tree = lapply(tree, function(x) structure(x, stopened = T))

ui <- fluidPage(
  tags$head(tags$script('
                        $("#reset").onlick(function() {
                        $("#tree").jstree("deselect_all");
                        }
                        ')),
  fluidPage(
    sidebarLayout(
      sidebarPanel(
        actionButton('reset', 'Reset nodes')
      ),
      mainPanel(
        shinyTree("tree", ),
        hr(),
        "Selected nodes:",
        verbatimTextOutput("idSelected")#,
      )
    )
  )
)

# server

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

  output$tree = renderTree({

    tree

  })


  output$idSelected <- renderPrint({
    str(get_selected(input$tree, format = "classid"))
  })


  # An observer is used to trigger a tree update when reset is clicked.
  observeEvent(input$reset, {

    updateTree(session,"tree", data = tree)

    print(get_selected(input$tree, format = "classid"))
  })
}

shinyApp(ui, server)

我尝试了以下JQuery无济于事:

$("#reset").onlick(function() {
                        $("#tree").jstree("deselect_all");
                        }

1 个答案:

答案 0 :(得分:2)

您可以点击重置按钮来更新reactiveVal,而不是直接引用get_selected提供的数据:

library(shiny)
library(shinyTree)

tree <- lapply(structure(list(a=list(a1=1,a2=2) , b="b"), stopened = TRUE) , function(x) structure(x, stopened = TRUE))

ui <- fluidPage(
  fluidPage(
    sidebarLayout(
      sidebarPanel(
        actionButton('reset', 'Reset nodes')
      ),
      mainPanel(
        shinyTree("tree", ),
        hr(),
        "Selected nodes:",
        verbatimTextOutput("idSelected")#,
      )
    )
  )
)

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

  treeSelection <- reactiveVal(list())

  output$tree = renderTree({
    tree
  })

  observeEvent(input$reset, {
    updateTree(session, "tree", data = tree)
    treeSelection(list())
  })

  observeEvent(input$tree, {
    treeSelection(get_selected(input$tree, format = "classid"))
  })

  output$idSelected <- renderPrint({
    treeSelection()
  })

}

shinyApp(ui, server)