Skip to content

R JavaScript binding

Gordon Woodhull edited this page Mar 1, 2015 · 9 revisions

An RCloud session runs on both client and server, and it is possible for R functions on the server to call JavaScript functions on the client, and vice versa.

The mechanism used is called an ocap, for Object Capability. In the context of RCloud, this just means a function with its closure, identified by an unguessable hash key. Generally you won't see or care about the value of this hash key, because there are convenience functions which make it look like you are just calling a function.

Calling JavaScript from R

In the context of writing [RCloud Extensions], the connection between R and JavaScript will start on the R side, with R code requesting JavaScript code to be installed.

Often, this code comes from a resource in an R package; it may also come from an asset in the RCloud notebook:

  • Use system.file to get the path to a resource in an R package, and paste(readLines(f), collapse='\n')) to read the file.
  • Use rcloud.get.asset to read the contents of a notebook asset

Then, install the code in the client by calling rcloud.install.js.module, which takes the module name and the source to install.

For example, most RCloud extensions contain a function that looks something like this, which combines loading the code from a package resource, and installing the source on the client:

  f <- function(module.name, module.path) {
    path <- system.file("javascript", module.path, package="rcloud.enviewer")
    caps <- rcloud.install.js.module(module.name,
                                     paste(readLines(path), collapse='\n'))
    caps
  }

The format of JavaScript rcloud.install.js.module is somewhat unique, and deserves some explanation.

Clone this wiki locally