-
Notifications
You must be signed in to change notification settings - Fork 143
R JavaScript binding
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.
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.assetto 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:
install.js.resource <- function(package.name, module.name, module.path) {
path <- system.file("javascript", module.path, package=package.name)
caps <- rcloud.install.js.module(module.name,
paste(readLines(path), collapse='\n'))
caps
}
The equivalent for installing JavaScript from an asset is
install.js.asset <- function(module.name, asset.name) {
caps <- rcloud.install.js.module(module.name, rcloud.get.asset(asset.name))
caps
}
The format of JavaScript code required by rcloud.install.js.module is particular, and deserves some explanation. Because the code will be evaluated on the client using, yes, eval, the code must be a single expression, without a terminating ;. It must also evaluate to a single function, or an object containing only functions.
Additionally, any JavaScript functions called from R will be called asynchronously: they take a function called a continuation as their last parameter, and only when the continuation is called does execution return to the R function.
Thus, the simplest valid JavaScript code that can be installed by RCloud is
(function(x, k) {
k();
})
Or, in object form:
({
f: function(x, k) {
k()
}
})