javascript - R Shiny 代码在发送到 Javascript 时会被执行多次

标签 javascript shiny

我有这个应用程序:

    #
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(includeScript("www/script.js"),

   # Application title
   titlePanel("Old Faithful Geyser Data"),

   # Sidebar with a slider input for number of bins 
   sidebarLayout(
      sidebarPanel(
         sliderInput("bins",
                     "Number of bins:",
                     min = 1,
                     max = 50,
                     value = 30)
      ),

      # Show a plot of the generated distribution
      mainPanel(
         plotOutput("distPlot")
      )
   )
)

# Define server logic required to draw a histogram
server <- function(session, input, output) {

   output$distPlot <- renderPlot({
      # generate bins based on input$bins from ui.R
      x    <- faithful[, 2] 
      bins <- seq(min(x), max(x), length.out = input$bins + 1)

      observe({
          if(input$bins > 25) {
              Message1 = input$bins
              session$sendCustomMessage("bla", Message1)
          }
      })

      # draw the histogram with the specified number of bins
      hist(x, breaks = bins, col = 'darkgray', border = 'white')
   })
}

# Run the application 
shinyApp(ui = ui, server = server)

我的 Oberserver 检查该值是否大于 25。我将该值发送到 Javascript。

    $( document ).ready(function() {
    Shiny.addCustomMessageHandler("bla", dosomething);

    function dosomething(Message1) {
        alert(Message1)
    }
});

代码运行完美,但是每次我更改 slider 时,代码似乎都比以前多执行一次。例如,更改 2 次后,我收到 3 条警报。为什么会发生这种情况?我可以采取什么措施来应对它?

最佳答案

之所以如此糟糕,是因为您的 observe() 位于 renderPlot() 函数内。一般来说,观察者不应该位于渲染函数内部,这几乎总是导致非常奇怪的未定义行为发生的原因!

只需将观察者移到渲染函数之外即可解决您的问题。这还解决了您没有提到的另一个问题,即警报框实际上显示的是上一个数字,而不是当前数字。

为了完整起见,这是正确的服务器代码:

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

  output$distPlot <- renderPlot({
    # generate bins based on input$bins from ui.R
    x    <- faithful[, 2] 
    bins <- seq(min(x), max(x), length.out = input$bins + 1)

    # draw the histogram with the specified number of bins
    hist(x, breaks = bins, col = 'darkgray', border = 'white')
  })


  observe({
    if(input$bins > 25) {
      Message1 = input$bins
      session$sendCustomMessage("bla", Message1)
    }
  })
}

关于javascript - R Shiny 代码在发送到 Javascript 时会被执行多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52842968/

相关文章:

css - 如何在 R shiny selectizeInput 组标题中设置字体颜色?

r - 从 Shiny ggplot 中的点击创建数据集

r - 如何在 Shiny Leaflet map 中将图层置于顶部

javascript - 如何向简单的 html 画廊添加标题

javascript - 如何针对鼠标悬停事件上的元素 id 值进行测试?

javascript - 动态加载 rel 属性中的链接。

r - 如何从 Shiny 的模块调用 Shiny 的模块?

javascript - 从页面检查 Firebug 以获取网络面板的结果

javascript - 谷歌地图不显示标记

rCharts 突出显示 Shiny 的图表不起作用