【发布时间】:2019-07-29 15:14:58
【问题描述】:
我想在选项卡/应用关闭之前显示确认模式,但前提是确实进行了更改。
我发现了一些有用的功能here,但每次我想关闭应用程序/选项卡时它们都会显示模式。在下面的示例中,我使用来自 @Matee Gojra 的 goodbye-function。
我想我可以将一个布尔值从 R 发送到 JavaScript,并且只在发生更改的情况下执行该函数。
但显然,如果我在函数中包含 if 条件,它就不再起作用了。
我怎样才能做到这一点,或者这不是故意的?
library(shiny)
js <- HTML("
var changes_done = false;
Shiny.addCustomMessageHandler('changes_done', function(bool_ch) {
console.log('Are changes done?');
console.log(bool_ch);
changes_done = bool_ch;
});
function goodbye(e) {
if (changes_done === true) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
//This is displayed on the dialog
e.returnValue = 'Are you sure you want to leave without saving the changes?';
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
}
window.onbeforeunload = goodbye;
")
ui <- fluidPage(
tags$head(tags$script(js)),
actionButton("add_sql", "Make Changes"),
verbatimTextOutput("sqls")
)
server <- function(input, output, session) {
sqlCmd <- reactiveVal(NULL)
## Simulate a Change
observeEvent(input$add_sql, {
sqlCmd(runif(1, 1, 1000))
})
output$sqls <- renderPrint({
req(sqlCmd())
sqlCmd()
})
## Are changes made? Send to JS
observe({
if (!is.null(sqlCmd())) {
session$sendCustomMessage("changes_done", 'true')
} else {
session$sendCustomMessage("changes_done", 'false')
}
})
}
shinyApp(ui, server)
当JS-sn-p中的if (changes_done === true) {}这个条件被注释掉或删除时,模态框会在关闭应用程序之前出现,但不会出现。
【问题讨论】:
标签: javascript r shiny