One listener for all updates

The Datastore API, launched in beta at DBX, gives JavaScript developers a straightforward way to keep app data in sync across devices and browsers. By attaching change listeners, you can react to modifications made by any other running instance of your app. In the JavaScript library, these listeners fire for both local and remote changes — so you can route all UI refreshes through a single handler rather than duplicating logic for each change source.

Consider a small app that displays three colored boxes, each with a text field for entering a hex color value. The Datastore API synchronizes changes to these boxes across all open instances of the app.

Updating the record, not the view

Each box is represented by a JavaScript ColoredBox object, which is bound to a record in the datastore. When the user edits the text field, the app calls the changed method to update the datastore record. Note that the UI color is deliberately not changed at this point — only the record is modified. The visual update is deferred to a separate update method:

function ColoredBox($el, record) {
    this.$square = $('.color-box', $el);
    this.$textbox = $('input', $el);
    this.record = record;
    this.update();
    this.$textbox.on('focusout', this.changed.bind(this));
}
 
ColoredBox.prototype.changed = function() {
    this.record.set('color', this.$textbox.val());
};
ColoredBox.prototype.update = function() {
    var color = this.record.get('color');
    this.$textbox.val(color);
    return this.$square.css('background', color);
};

Putting the change listener to work

To keep the display in sync with the datastore records, the app registers a change listener at initial page load. That listener calls update on the appropriate ColoredBox whenever any record is altered:

datastore.recordsChanged.addListener(function(event) {
    event.affectedRecordsForTable('colors').forEach(function(record) {
        return colored_boxes[record.get('order')].update();
    });
});

Because this handler runs on every record change, the same code path handles both local edits from typing in a color and remote edits arriving from another instance of the app. No additional wiring is needed to distinguish between the two.

Try the demo

You can test the app in your browser or browse the complete source on GitHub.

Play with the appView the source code

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