server.R

The server.R file runs as follows:

function(input, output, session) { 
  output$randomNumber = renderText({ 
    theNumber = sample(1:input$pickNumber, 1) 
    session$sendCustomMessage(type = 'sendMessage', 
message = theNumber) return(theNumber) }) output$theMessage = renderText({ return(input$JsMessage) }) }

The first thing to note here is the use of function(input, output, session){...} instead of the function(input, output){...} that we are used to seeing. The addition of a session argument adds a considerable amount of functionality to Shiny applications. In this case, it allows us to send messages to JavaScript. There is more on the functionality of the session argument in the next chapter, Chapter 6, Dashboards.

The first function here carries out two tasks. First, it takes the number that the user selected on the slider and picks a random number between 1 and that number. It sends that number straight to JavaScript using the session$sendCustomMessage function (which the session argument we mentioned previously enables). The sendCustomMessage() function is defined within Shiny; it is placed after session$ in order to tie it to the session defined in the shinyServer(function(input, output, session){...}) function. Finally, it returns the number to Shiny, just like in a standard application, ready to be placed in the output slot, which ui.R sets up.

The second function receives the JavaScript message. It's very easy to access, the Shiny function within JavaScript writes it to the standard input$xxx variable name, which we are used to seeing throughout the book. As is now plain, a lot of the work in this application is being done within the JavaScript file. Let's take a look.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset