JavaScript and Shiny

The connection between JavaScript and Shiny is another reason to recommend RStudio as an IDE because it performs beautiful syntax highlighting on JavaScript straight out of the box (although, clearly, other text editors and IDEs may do this or be easily configured to do so).

Before we proceed, it's worth reviewing the difference between server and client-side code and what they're used for. JavaScript gained popularity as a client-side language, which ran on web browsers and added interactivity to websites that would otherwise be static HTML and CSS files, which were downloaded from servers.

It has found increasing use on the server side (for example, with Node.js), but we are going to use it on the client side and so will not consider this any further. So, in this case, JavaScript is running on the client side. The server side in this case, of course, is R, and specifically the commands are to be found in the server.R file. Shiny and JavaScript (and, by extension, jQuery) can, as server and client respectively, pass things back and forth between themselves as you wish.

Also, it's worth noting that there are two ways for Shiny and JavaScript to interact with each other.

The first is perhaps the simplest and will be considered first. Because Shiny and JavaScript can both read and write to the web page (that is, to the Document Object Model (DOM), it is quite simple for them to interact with each other on the web page. The DOM is a way of organizing objects in HTML, XHTML, and XML documents, in which elements are referenced within a tree structure.

A detailed discussion is well outside the scope of this book; suffice to say that if you are going to use JavaScript with Shiny or HTML, you will need to learn about the DOM and how to get and set attributes within it.

The second way in which Shiny and JavaScript can interact is when it's easier or better to send messages directly between the server and client. Although in theory, you could use the <input type="hidden"> tag of HTML and pass messages on the DOM without showing them to the user, it will often be easier to cut out the middle man and send the information directly, particularly when the message is complicated (a large JSON object, for instance).

We will look at sending messages directly after the first example. 

First, as a warm-up, we will look at using JavaScript to read the DOM generated by Shiny and perform some client-side processing, before writing the changes back to the DOM.

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

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