Integrating the Dropbox Datastore API with Ractive.js

// By Steve Marx • Aug 28, 2013

Update: The Sync and Datastore SDK has been deprecated. Learn more here.

I recently came across Ractive.js, a nice JavaScript library created by Rich Harris for data binding and efficient DOM updates. Ractive is strictly about updating the DOM when data changes, so it doesn't address where the data lives or how it is changed. This makes it a perfect candidate to combine with a storage and syncing technology like the Datastore API.

To see what such a combination would look like, I built Ractive Datastore, a 40-line library that provides two-way databinding courtesy of Ractive.js with cross-device syncing courtesy of the Datastore API. To see how it works, try the demo at ractiveds.site44.com.

Storing key/value pairs in datastores

The Datastore API supports a data model based on tables, records, and fields. Each table consists of a number of records (each with a unique ID), and each record consists of fields with typed values. For my data-binding uses, though, I really just wanted to store key/value pairs. I settled on a scheme with a single table. Inside that table, each record stores a single key/value pair, with the key being the record ID and the value being the value of a single field (called "value"). For example, to update the key/value pair recipient=Steve, I could use this line of JavaScript:

datastore.getTable("ractivedatastore").get("recipient").set("value", "Steve");

Note that this code assumes that a record with the ID “name” already exists. I make sure that each key exists during the initialization step, which is keeping in line with the way Ractive.js works. The goal is to initialize a key/value pair in the table with a default value but never to overwrite any existing value in the table. Typically, when a record is inserted into a datastore table, it gets a randomly assigned record ID. To support my data model of key/value pairs, I need to instead assign my own record ID. This is possible with the getOrInsert method, as in the following code:

var defaultName = "Bob";
datastore.getTable("ractivedatastore").getOrInsert("recipient", {value: defaultName});

If there’s already a record with the ID "recipient," this code will just return the existing record. If, however, there is no such record, this will insert a new one and set the value field to "Bob."

Get the library

The full source code for the library is available in the Ractive Datastore project on GitHub, and you can play with a demo at ractiveds.site44.com.

// Copy link