R shiny observeEvent在模块中不起作用

时间:2018-06-01 15:47:29

标签: r module shiny

提前感谢您的帮助。我试图将我的问题归结为我可以构建的应用程序的简单。我有一个函数sliderResetInput,它调用observeEvent并返回一些UI元素。我可以在模块外部使用sliderResetInput(将在下面演示),但我不能在模块中使用它。我认为这是一个围绕我的输入包装命名空间的问题,但我认为ID都在这里查看。这是怎么回事?需要注意的是,虽然这个应用程序对于这个应用程序似乎不必要地复杂化,但我需要一个更大的应用程序的结构。

这有效:

library(shiny) # Version 1.0.5

sliderResetInput = function(id, input, output, session) {

  observeEvent(input[[paste0(id, "_reset_slider")]], 
               updateSliderInput(session = session, inputId = paste0(id, "_slider"), value = c(0, 10)))

  out = list(
    sliderInput(inputId = paste0(id, "_slider"), label = "Slider", min = 0, max = 10, value = c(0, 10)),
    actionButton(inputId = paste0(id, "_reset_slider"), label = "Reset slider")
  )

  return(out)
}


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

  getSliders = reactive(sliderResetInput(id = "test1", input, output, session))

  output$sliders = renderUI(getSliders())

  observeEvent(input$browser, browser())
}


ui <- fluidPage(
  uiOutput(outputId = "sliders"),
  actionButton(inputId = "browser", "Click me to go into browser()")
)


shinyApp(ui = ui, server = server, options = list(launch.browser = T))

使用相同的sliderResetInput()函数,这不起作用:

library(shiny) # Version 1.0.5

sliderResetInput = function(id, input, output, session) {

  observeEvent(input[[paste0(id, "_reset_slider")]], 
               updateSliderInput(session = session, inputId = paste0(id, "_slider"), value = c(0, 10)))

  out = list(
    sliderInput(inputId = paste0(id, "_slider"), label = "Slider", min = 0, max = 10, value = c(0, 10)),
    actionButton(inputId = paste0(id, "_reset_slider"), label = "Reset slider")
  )

  return(out)
}


myModuleUI = function(id) {
  ns = NS(id)

  tagList(
    uiOutput(outputId = ns("sliders"))
  )
}



myModule = function(input, output, session) {
  ns = session$ns

  getSliders = reactive(sliderResetInput(id = ns("test1"), input, output, session))

  output$sliders = renderUI(getSliders())
}

server <- function(input, output, session) {
  callModule(myModule, id = "A")
  observeEvent(input$browser, browser())
}


ui <- fluidPage(
  myModuleUI(id = "A"),
  actionButton(inputId = "browser", "Click me to go into browser()")
)


shinyApp(ui = ui, server = server, options = list(launch.browser = T))

有谁知道这里发生了什么?

感谢您的时间!

1 个答案:

答案 0 :(得分:0)

您只需在窗口小部件的ID前面添加前缀。那就是:

sliderResetInput = function(id, NSid, input, output, session) {

  observeEvent(input[[paste0(id, "_reset_slider")]], {
    updateSliderInput(session = session, inputId = paste0(id, "_slider"), value = c(0, 10))
  })

  out = list(
    sliderInput(inputId = paste0(NSid, "_slider"), label = "Slider", min = 0, max = 10, value = c(0, 10)),
    actionButton(inputId = paste0(NSid, "_reset_slider"), label = "Reset slider")
  )

  return(out)
}

  getSliders = reactive(sliderResetInput(id = "test1", NSid = ns("test1"), input, output, session))