我在下面创建了一个最小的代码来重现我在应用程序中遇到的问题。
我想做的是对多个输入调用相同的方法,其中存在observeEvent一个actionButtonfor ,其中仅在调用内部调用的函数后才创建。我面临的问题是,添加此from来调用具有多个输入的 后,永远不会被调用。如果我删除这个按钮,就会被调用。以下是我的代码:observeEventmodalDialogobserveEventactionButtonmodalDialogobserveEventobserveEventobserveEvent
library(shiny)
#Function called from shiny server
func <- function(input,output){
if(is.null(input$txt_Modal)){
output$txt <- renderText("No Text Entered Yet!")
showModal(modalDialog(title = "Choose Survival Time",
textInput(inputId = "txt_Modal", "Enter text:"),
easyClose = FALSE, footer = actionButton(inputId = "btn_Modal_OK","OK")))
}else{
output$txt <- renderText({input$txt_Modal})
}
}
##UI code
ui <- fluidPage(
actionButton(inputId = "btn", label = "Enter function and Print Value"),
textOutput(outputId = "txt")
)
##Server code
server <- function(input, output, session){
observeEvent({
input$btn
input$btn_Modal_OK
},{
func(input, output)
})
}
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)
这是在函数中创建input$btn_Modal_OK的按钮。从代码中删除后,代码将按预期工作。ModalDialogfuncinput$btn_Modal_OKobserveEvent
我能想到发生这种情况的原因是因为input$btn_Modal_OK在NULL程序开始时。我认为消除此错误的一种方法是编写不同的observeEventforinput$btn_Modal_OK但我的实际代码中有很多行代码observeEvent,我不想在另一个代码中重写observeEvent并使代码变得庞大。
请注意,这不是我在实际应用程序中所做的,我刚刚编写了此代码来重现问题。非常感谢任何帮助!
问题是在初始化时input$btn从 切换NULL到0并触发模式,但您func只想在实际按下时触发input$btn,即当它的值等于1或以上时。这就是为什么这可以解决您的问题:
observeEvent(c(input$btn, input$btn_Modal_OK), {
validate(need(input$btn > 0, ''))
func(input, output)
})
Run Code Online (Sandbox Code Playgroud)