shinyTree - 运行 树展开后起作用

shinyTree - run function once tree is expanded

让我们假设我有一个像

这样的最小工作示例
library(shiny)
library(shinyTree)

ui <- fluidPage(
  shinyTree("tree", contextmenu = TRUE, search = TRUE, unique = TRUE, sort = TRUE)
)

server <- function(input, output, session) {
  
  output$tree <- renderTree({
    list(
      root1 = "",
      root2 = list(
        SubListA = list(leaf1 = "", leaf2 = "", leaf3=""),
        SubListB = list(leafA = "", leafB = "")
      ),
      root3 = list(
        SubListA = list(leaf1 = "", leaf2 = "", leaf3=""),
        SubListB = list(leafA = "", leafB = "")
      )
    )
  })
}

shinyApp(ui, server)

生成像

这样的 shinyTree (jstree)

如果我在展开树时单击左侧的小三角形之一(不一定要选择任何东西),是否可以 运行 一个函数。我正在考虑将 shinyjs 包与 onclick 事件一起使用,但并没有真正管理那么多

您可以使用 jstree events 来触发一个闪亮的观察者来执行一个函数。在下面的例子中,JS代码将input$expanded_node的值更新为扩展节点的名称,然后触发关联的观察者。

library(shiny)
library(shinyTree)

ui <- fluidPage(
  shinyTree("tree", contextmenu = TRUE, search = TRUE, unique = TRUE, sort = TRUE),
  tags$script(HTML('
    // "triggered when a node is opened and the animation is complete"
    $("#tree").on("after_open.jstree", function (e, data) {
      Shiny.onInputChange("expanded_node", data.node.text, {priority: "event"});
    });
  ')),
  verbatimTextOutput("function_result")
)

server <- function(input, output, session) {
  
  output$tree <- renderTree({
    list(
      root1 = "",
      root2 = list(
        SubListA = list(leaf1 = "", leaf2 = "", leaf3=""),
        SubListB = list(leafA = "", leafB = "")
      ),
      root3 = list(
        SubListA = list(leaf1 = "", leaf2 = "", leaf3=""),
        SubListB = list(leafA = "", leafB = "")
      )
    )
  })
  
  result <- reactiveValues()
  
  observeEvent(input$expanded_node, {
    # execute a function ...
    result$data <- runif(1, 1, 1e6)
    result$node <- input$expanded_node
  })
  
  output$function_result <- renderPrint({ 
    paste("Node:", result$node, ", Result:", result$data)
  })
}

shinyApp(ui, server)