2017-09-13 146 views
0

我的目標是建立菜單,其內容是動態生成的,用戶只能看到menuItems/menuSubItems從頂部開始到所選擇的一個(「next」按鈕將用於到達下一個尚未顯示的menuItems/menuSubItems;如果選擇了任何可用的menuItems/menuSubItems菜單,則應該重新生成菜單,以便選擇最後一個可用的menuItems/menuSubItems)。所以我將不得不玩startExpanded的論點,但這不是這個問題的一部分。閃亮:閃亮的儀表板中的renderMenu和observeEvent衝突(側邊菜單)

我面臨的問題是相互連接renderMenuobserveEvent(檢查所選menuItem/menuSubItem)。以下是代碼:

library(shiny) 
library(shinydashboard) 

menu_generator <- function(selected = NULL, expanded = NULL){ 

    print("menu_generator") 

    output <- sidebarMenu(

    menuItem("Charts1", icon = icon("bar-chart-o"), 
      menuSubItem("AAdashboard", tabName = "AAdashboard"), 
      menuSubItem("BBdashboard", tabName = "BBdashboard") 
    ), 
    menuItem("Charts2", icon = icon("bar-chart-o"), 
      menuSubItem("DDdashboard", tabName = "DDdashboard"), 
      menuSubItem("EWidgets", tabName = "EWidgets") 
    ) 

) 

    return(output) 
} 

ui <- dashboardPage(
    dashboardHeader(title = "Test"), 
    dashboardSidebar(sidebarMenu(
    sidebarMenuOutput("menu_output") 
)), 
    dashboardBody(
    tabItems(
     tabItem(tabName = "AAdashboard", 
       h2("ADashboard tab content") 
    ), 

     tabItem(tabName = "BBdashboard", 
       h2("BWidgets tab content") 
    ), 

     tabItem(tabName = "DDdashboard", 
       h2("DWidgets tab content") 
    ), 

     tabItem(tabName = "EWidgets", 
       h2("EWidgets tab content") 
    ) 
    )) 
) 


server <- function(input, output) { 

    output$menu_output <- renderMenu({ 
    print("output$menu_output") 
    sidebarMenu(menu_generator(), 
       id = "my_menu") 

    }) 

    observeEvent(input$my_menu, { 

    print("observer") 

    print(input$my_menu) 
    print(input$sidebarItemExpanded) 

    output$menu_output <- renderMenu({ 
     sidebarMenu(menu_generator(), 
        id = "my_menu") 
    }) 
    }) 


} 

shinyApp(ui, server) 

場景:展開圖表2,然後單擊「DDdashboard」。

在控制檯:

[1] "observer" 
[1] "DDdashboard" 
[1] "Charts2" 
[1] "menu_generator" 
[1] "observer" 
[1] "AAdashboard" 
NULL 
[1] "menu_generator" 

「觀察者」 之稱的兩倍(如後果 「menu_generator」 也),所以這造成意外行爲。我的理解是,原因是renderMenu。問題是 - 如何防止Shiny在這種情況下調用「觀察者」兩次?另請注意,在第二個電話input$my_menu =「AAdashboard」。

回答

-1
observeEvent(input$sidebarItemExpanded == 'DDdashboard',{ 

print("DDdashboard_selected") 

    })