闪亮:观察全局变量的变化 [英] Shiny: observe change in global variable
问题描述
我正在用Shiny制作一个非常简单的游戏.基本上,每个玩家都在自己的会话中玩游戏,但是他们共享1个全局变量来跟踪每个玩家的得分.
I am making a very simple game in Shiny. Basically every player plays in their own session, but they share 1 global variable to keep track of the scores of each player.
我认为我正在成功地通过会话更新全局分数"变量,但是由于某些(可能是愚蠢的)原因,我无法使全局变量充当反应性值(即自动触发updateActionButton).下面的最小代码:
I think I'm succeeding having sessions update the global 'scores' variable, but for some (probably dumb) reason I cannot get the global variable to act as a reactive value (i.e. automatically triggering updateActionButton). Minimal code below:
工作示例:
score <- c(100)
ui <- fluidPage(
titlePanel("Hello Shiny!"),
mainPanel(
actionButton("increase_score", label = " increase score player 1 "),
verbatimTextOutput("show_score_p1")
)
)
# Server logic
server <- function(input, output){
observeEvent(input$increase_score,{
score[1] <- score[1]+10
})
output$show_score_p1 <- renderText({paste(score[1])})
}
shinyApp(ui,server)
我尝试了几种方法来使我的全局分数"具有反应性,即makeReactiveBinding(score),但无济于事.有任何想法吗?绝对感觉我想念一些超显而易见的东西
I tried a couple of methods to try and make my global 'score' to be reactive, i.e. makeReactiveBinding(score), but to no avail. Any ideas? Definitely feels like I'm missing something super-obvious
推荐答案
使用可以使用名为reactiveValues
library(shiny)
ui <- fluidPage(
titlePanel("Hello Shiny!"),
mainPanel(
actionButton("increase_score", label = " increase score player 1 "),
verbatimTextOutput("show_score_p1")
)
)
score<-reactiveValues(a=100)
# Server logic
server <- function(input, output){
observeEvent(input$increase_score,{
score$a <- score$a+10
})
output$show_score_p1 <- renderText({
score$a
})
}
shinyApp(ui,server)
这篇关于闪亮:观察全局变量的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!