我编写了这段代码,用于在textarea上应用编辑器类,其中id =" textBox"。应用编辑器类需要运行javascript代码,并且正在寻找一种方法将javascript运行绑定到启动应用程序的事件(或应用程序加载时)。基本上我想在应用程序加载时运行js,而不需要将它绑定到按钮按下,因为它目前已实现。我不知道如何引用app load事件。按钮实现是我能想到的最好的,并且在询问之前花了相当多的时间。
有关如何运行代码的详细信息,请参阅this问题。
如果您需要更多信息,请告诉我。很乐意帮忙。提前谢谢。
library(shiny)
library(shinyjs)
if (interactive()) {
ui <- shinyUI(
fluidPage(
useShinyjs(),
tags$head(tags$title("Title"),
tags$link(rel = "stylesheet", href = "codemirror.css"),
tags$link(rel = "stylesheet", href = "cobalt.css"),
tags$script(src = "codemirror.js"),
tags$script(src = "r.js")
),
actionButton("btn1","Click to see code"),
uiOutput(outputId = "textStringToDisplay")))
server <- function(input, output){
output$textStringToDisplay <- renderUI(
tags$textarea(id="textBox", name = "Feedback", paste0(sample(letters,15),collapse = "")))
ButtonPressCounter <- 0
observeEvent(input$btn1,
{
ButtonPressCounter <<- ButtonPressCounter + 1 # Need it to happen only once
if(ButtonPressCounter <= 1){
shinyjs::runjs(
'var editorR = CodeMirror.fromTextArea(textBox, {
mode: "r",
lineNumbers: true,
smartindent: true});
editorR.setOption("theme", "cobalt");
editorR.setSize("100%","100%");')
}
})
}
shinyApp(ui = ui, server = server) }
答案 0 :(得分:2)
要在打开应用时运行javascript代码,请不要需要将代码放在观察者中。如果使用以下代码替换服务器,您将看到日志将包含行"hello, this code has run."
server <- function(input, output){
output$textStringToDisplay <- renderUI(
tags$textarea(id="textBox", name = "Feedback", paste0(sample(letters,15),collapse = "")))
shinyjs::runjs(
'console.log("hello, this code has run.");
var editorR = CodeMirror.fromTextArea(textBox, {
mode: "r",
lineNumbers: true,
smartindent: true});
editorR.setOption("theme", "cobalt");
editorR.setSize("100%","100%");')
}
虽然日志中的下一行是ReferenceError: Can't find variable: CodeMirror
,但我想您的代码中缺少某些内容?
希望这有帮助!