Binding Ractive.js Views to Dropbox Datastores

Ractive.js is a lightweight JavaScript library by Rich Harris that handles data binding and efficient DOM updates. Its scope is deliberately narrow: Ractive only cares about reflecting data changes in the DOM, and it leaves the questions of where data is stored and how it's modified entirely to the developer. That separation of concerns makes Ractive a natural fit for pairing with a storage and sync backend such as the Dropbox Datastore API.

To explore that combination, I built Ractive Datastore, a compact library (about 40 lines) that wires Ractive.js for two-way data binding to the Datastore API for cross-device syncing. A live demo is available at ractiveds.site44.com.

A simple key/value model on top of tables and records

The Datastore API's data model is built around tables, records, and fields. A table holds many records, each with a unique ID, and each record contains fields with typed values. For a data-binding use case, though, the natural abstraction is a flat set of key/value pairs. The library maps that abstraction onto the API by using a single table where every record stores one pair: the record ID acts as the key, and a field named "value" holds the value. A typical update looks like this:

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

That code assumes a record with the ID "name" already exists, which is why initialization is an explicit step. The initialization routine ensures that each key has a default record but never overwrites data already present in the table. The challenge is that the Datastore API normally assigns random record IDs on insert. To use the ID as a application-level key, the insert needs to happen with a caller-supplied ID. The API's getOrInsert method makes that possible:

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

When a record with the ID "recipient" is already present, getOrInsert simply returns it. If no such record exists, a new one is inserted and its "value" field is initialized to "Bob".

Source and demo

The complete library source is on GitHub in the Ractive Datastore repository, and the demo is live at ractiveds.site44.com.

Note: The Sync and Datastore SDKs have since been deprecated. See the deprecation announcement for details.