非常好的问题.这是我使用方式的一个例子; 这个应用程序显示了一个ggplot,用户在文本框中给出了ggplot的标题 - 但标题更改仅在按下"Return"时才会响应:
js <- '
$(document).on("keyup", function(e) {
if(e.keyCode == 13){
Shiny.onInputChange("keyPressed", Math.random());
}
});
'
shinyApp(
ui = bootstrapPage(
tags$script(js),
textInput("title", label = "Title"),
plotOutput("ggplot")
),
server = function(input, output, session){
Title <- reactiveVal()
observeEvent(input[["keyPressed"]], {
Title(input[["title"]])
})
output[["ggplot"]] <- renderPlot({
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
geom_point() +
ggtitle(Title())
})
}
)
Run Code Online (Sandbox Code Playgroud)
这个Javascript代码:
$(document).on("keyup", function(e) {
if(e.keyCode == 13){
Shiny.onInputChange("keyPressed", Math.random());
}
});
Run Code Online (Sandbox Code Playgroud)
创建一个新的Shiny输入,即input$keyPressed在任何地方按下"Return"键时接收一个随机数.
然后我定义一个反应值,它取input$title用户在文本框中给出的值,仅在input$keyPressed更改时:
Title <- reactiveVal()
observeEvent(input[["keyPressed"]], {
Title(input[["title"]])
})
Run Code Online (Sandbox Code Playgroud)
最后我将此反应值传递给ggtitle:
output[["ggplot"]] <- renderPlot({
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
geom_point() +
ggtitle(Title())
})
Run Code Online (Sandbox Code Playgroud)