如何从Shiny将值传递给浏览器以便JavaScript可以使用它们?

时间:2016-02-11 22:35:00

标签: javascript r shiny

我想让R Shiny与Javascript交流。我已经成功创建了一个查找span标签的js脚本,并将其替换为"他"或者"她"取决于我在server.r中提供的性别信息。因此,如果candidateGender == 1,JavaScript会插入"她"对于candidateGender == 0,JS插入"他"。

如果我直接从UI.r使用HTML()函数,这是有效的。但是,当我从server.r通过renderText传递给htmlOutput组合时,它也不起作用。

以下是三个脚本。请注意,JavaScript必须插入名为' www'的文件夹中。并保存在与ui和服务器文件相同的文件夹中。

UI:

library(shiny)

    ui <- fluidPage(
      tags$head(tags$script(src="pronoun_selector.js")),
      ### this works
                          HTML('<strong> This works: </strong>
                                <p>
                                    He/She: 
                                    <span class="replace-text-pronoun">he/she</span> 
                                    His/Her: 
                                    <span class="replace-text-posessive">his/her</span> 

                                </p>'),

       ### this doesn't                   
                          HTML('<strong> This does not work: </strong>'),
                          htmlOutput("statement")
    )

SERVER:

library(shiny)


server <- function(input, output, session) {
  #select gender
  candidateGender <-  "1" #1 == Female; 2 == Male

  #pass to customMessage handler
  observe({
    session$sendCustomMessage('replaceTextCallbackHandler', candidateGender) #### set up the callback handler
  })


  output$statement <- renderText({
    'He/She: 
     <span class="replace-text-pronoun">he/she</span> '
    }) 

}

JavaScript(在文件夹www中另存为pronoun_selector.js):

$(document).ready(function() {
  Shiny.addCustomMessageHandler("replaceTextCallbackHandler",     
    function(candidateGender) { //candidateGender is set in server.r

      var pronounTextF = 'she';
      var pronounPosessiveTextF = 'her';
      var pronounTextM = 'he';
      var pronounPosessiveTextM = 'his';

      var pronouns = $('.replace-text-pronoun');
      var pronounsPosessive = $('.replace-text-posessive');

      if (candidateGender === '0') {
        pronouns.text(pronounTextM);
        pronounsPosessive.text(pronounPosessiveTextM);
      }
      else if (candidateGender === '1') {
        pronouns.text(pronounTextF);
        pronounsPosessive.text(pronounPosessiveTextF);
      }
      else {
        console.log(candidateGender);
      }
    }
  );
});

感谢任何帮助。

0 个答案:

没有答案