【问题标题】:shinyTree - run function once tree is expandedshinyTree - 一旦树展开就运行函数
【发布时间】:2021-11-14 09:07:20
【问题描述】:

假设我有一个最小的工作示例,例如

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)

它会生成一个类似闪亮的树(jstree)

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

【问题讨论】:

    标签: r shiny jstree shinytree


    【解决方案1】:

    你可以使用jstreeevents 来触发一个闪亮的观察者来执行一个函数。在下面的例子中,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)
    

    【讨论】:

    • 这真是太棒了,谢谢。还有没有办法确定打开了哪个节点?
    • 我更新了答案以返回展开的节点。
    猜你喜欢
    • 2021-12-02
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多