【发布时间】:2019-08-08 16:04:38
【问题描述】:
在我的应用程序中,我将使用insertUI 动态创建一个模块。我正在尝试找到一种方法来捕获此模块的输出。在下面的应用程序中,有一个由textInput 元素组成的简单模块。服务器部分返回此textInput 元素的值并报告它处于活动状态。我正在尝试捕获此返回值。
我试图创建一个reactiveValues 对象来获取模块的输出,但是当输入改变时这个对象似乎没有更新。模块代码本身正在运行,因为我收到来自模块内部的消息,但检查reactiveValues 的外部观察命令仅在重新创建时执行。如何从模块外部获取这些值
library(shiny)
# a module that only has a text input
moduleUI = function(id){
ns = NS(id)
tagList(
# the module is enclosed within a div with it's own id to allow it's removal
div(id = id,
textInput(ns('text'),label = 'text'))
)
}
# the module simply returns it's input and reports when there is a change
module = function(input,output,session){
observeEvent(input$text,{
print('module working')
})
return(input$text)
}
# ui is iniated with add/remove buttons
ui = fluidPage(
actionButton('add','+'),
actionButton('remove','-')
)
server = function(input, output,session) {
# number of ui elements already created
uiCount = reactiveVal(0)
moduleOuts = reactiveValues()
observeEvent(input$add,{
# count the UI elements created to assign new IDs
uiCount(uiCount()+1)
# insert module UI before the add/remove buttons
insertUI('#add',
'beforeBegin',
moduleUI(paste0("module",uiCount())))
# failed attempt to get the output
moduleOuts[[as.character(uiCount())]] = callModule(module,id = paste0("module",uiCount()))
})
observeEvent(input$remove,{
# if remove button is pressed, remove the UI and reduce the UI count
removeUI(
selector = paste0("#module",uiCount())
)
uiCount(uiCount()-1)
})
# simple test
observe({
print(moduleOuts[['1']])
})
# test to get all values
observe({
seq_len(uiCount()) %>% sapply(function(i){
print(moduleOuts[[as.character(i)]])
})
})
}
shinyApp(ui = ui, server = server)
【问题讨论】: