我有这个应用程序:
#
# 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/