Using observe function in shiny R

帅比萌擦擦* 提交于 2019-12-23 03:13:34

问题


I am trying to send the value of a JavaScript variable from ui.R to Server.R whenever it is changed. When a user clicks on a link, its href value is alerted . Till here it works fine. The links are of the form

<a href="something.com" onclick=\"clickFunction(this.href); return false;\" target=\"_blank\">Sample link </a>

Now, the href value is stored in variable link in ui.R . I am sending the value of link to server.R using Shiny.onInputChange function.

But the observe function in server.R is not giving me any value. Please tell me how to do this by using observe function or any other way if possible.

ui.r

library(shiny)
shinyUI(fluidPage(

  tags$script(HTML("
                      function clickFunction(link){
                          alert(link); 
                          Shiny.onInputChange(\"linkClicked\",link);   
                      }
                     "))

//rest of the code which is not related

)

server.R

library(shiny)

shinyServer(function(input, output) {

  observe({
    input$linkClicked
    print(input$linkClicked)
  })
})

回答1:


I don't really fully understand where the link is coming from and how the app looks since you didn't provide enough code (for example: what does it mean "variable in the UI"?). But here's a small example that shows how the javascript sends info to the server successfully. I'm using the shinyjs package which is a package I wrote.

library(shinyjs)
jscode <- "
shinyjs.clickfunc = function(link) {
  alert(link);  
  Shiny.onInputChange('linkClicked', link);
}"

runApp(shinyApp(
  ui = fluidPage(
    useShinyjs(),
    extendShinyjs(text = jscode),
    textInput("link", ""),
    actionButton("btn", "submit")
  ),
  server = function(input, output, session) {
    observeEvent(input$btn, {
      js$clickfunc(input$link)
    })
    observe({
      input$linkClicked
      print(input$linkClicked)
    })
  }
))

EDIT:

If I understand correctly how the links are generated, this works

runApp(shinyApp(
  ui = fluidPage(
    tags$script(HTML("
                      function clickFunction(link){
                          alert(link); 
                          Shiny.onInputChange('linkClicked',link);   
                      }
                     ")),
    tags$a(href="www.google.com", onclick="clickFunction('rstudio.org'); return false;", "click me")
  ),
  server = function(input, output, session) {
    observe({
      input$linkClicked
      print(input$linkClicked)
    })
  }
))


来源:https://stackoverflow.com/questions/31375480/using-observe-function-in-shiny-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!