首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >shinyTree -树展开后运行函数

shinyTree -树展开后运行函数
EN

Stack Overflow用户
提问于 2021-09-20 16:46:10
回答 1查看 50关注 0票数 0

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

代码语言:javascript
复制
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事件一起使用,但实际上并没有管理那么多

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-20 18:06:19

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

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69258124

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档