如何加载闪亮的应用程序时触发JS脚本

问题描述 投票:1回答:1

我编写了这段代码,用于在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) }
javascript r shiny codemirror shinyjs
1个回答
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,但我想你的代码中缺少一些东西?

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.