Simperium.js

Introduction

Adding Simperium to your web app can help in a variety of situations:

  • You're building a native iOS version of your app that needs to stay in sync with the web version of your app.
  • You're building a mobile app using web technologies, in particular JavaScript.
  • You're building a web app that needs realtime collaboration.

Use any frameworks like Backbone.js? You can use them with Simperium.js to sync your models automatically.

How it Works

You start by initializing Simperium and registering callbacks on a bucket. A bucket is just a place to put objects of a particular type, for example Todo items.

Thereafter, Simperium keeps the bucket's data persisted and in sync. You can react to incoming changes by registering callbacks. You can save local changes at any time, and Simperium does the work to sync those changes efficiently.

On startup you'll get notifications for any existing objects in the bucket, you can keep track of these objects in a simple dictionary or array or even a Backbone.Collection. Whenever an object is changed locally you call update to save it. Whenever you get a notify event, you should look up the id and update the object (as well as any UI). You'll want to implement the local callback so that Simperium can get the local state of an object at any time.

Note— If you're testing a page locally, be sure to use a local web server. Browsers typically prevent cross-domain access when loading pages from a local file. If you have python, you can start a local web server in any directory by using this command:

>>> python -m SimpleHTTPServer 8080

Using Simperium.js

Link to Simperium.js from your HTML page:

<script type="text/javascript" src="https://js.simperium.com/v0.1/"></script>

Looking for the full source code? It's hosted on GitHub.

Simperium.js includes code from google-diff-match-patch to merge text and uses SockJS to maintain a persistent connection to our servers.

To start Simperium, you need to provide an application id and an access token.

Get the application id and the default API key from the dashboard after you add your app.

Then to get an access token, use the API key and application id with the authorize call. Then you can create a bucket, register your callbacks, and start it.

var simperium = new Simperium('SIMPERIUM_APP_ID', { token : 'SIMPERIUM_ACCESS_TOKEN'});
var bucket = simperium.bucket('todo');
bucket.on('notify', function(id, data) {
    console.log("object "+id+" was updated!");
    console.log("new data is:");
    console.log(data);
});
bucket.on('local', function(id) {
    console.log("request for local state for object "+id+" received");
    return {"some": "json"};
});
bucket.start();

If your access token is invalid or expired, the error event will be triggered with a parameter of 'auth'.

notify

You register the notify callback so you know when Simperium has updated some data. It's called when the bucket is first loaded to let you know what objects already exist, and also when a remote change is made to any object in the bucket. It receives id to identify the object, along with the object's data in JSON format. Typically you'll use this callback to update your UI.

It's your responsibility to track your own objects. You can lookup an object that changed using id, and then make your changes to that object using data.

local

You should register the local callback if you have data that will be changing locally. This is how you expose your data to Simperium so it can resolve changes that arrive from somewhere else.

Given a unique id, you return the corresponding object.

update

Call update on your bucket to inform Simperium that an object has changed and should be synced or to create a new object in the bucket. You pass an object and, optionally, a unique id. Call this function whenever your object has changes you want to sync. Simperium figures out what has changed and syncs just the changes.

Authentication

Simperium provides a default system for user accounts. In order to sync a user's data, you need to create a unique user token. You can use an API endpoint to do this. A successful call returns an access token that you can pass as an argument when you create a new Simperium instance.

To authenticate a user, add the app ID generated when you added your app and send a post message to the auth endpoint:

https://auth.simperium.com/1/{SIMPERIUM_APP_ID}/authorize/

To create a user, you pass the same parameters to the auth endpoint ending in /create/:

https://auth.simperium.com/1/{SIMPERIUM_APP_ID}/create/

Both take the following parameters in a JSON object: username, and password and require the X-Simperium-API-Key header.

Note the API key to use in this X-Simperium-API-Key header can be found on your application dashboard. Also note that username currently must be an email address. More details in the HTTP API documentation.

Sample Authentication using jQuery

You may wish to generate an access token dynamically based on the user from the page. This is some sample code that will do that using jQuery's ajax method:

You'll need your application id, and an API key (both from your dashboard), and the username and password.

    var url = "https://auth.simperium.com/1/"+SIMPERIUM_APP_ID+"/authorize/";
    $.ajax({
        url: url,
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({"username":"username", "password":"password"}),
        beforeSend: function(xhr) {
            xhr.setRequestHeader("X-Simperium-API-Key", "SIMPERIUM_API_KEY");
        },
        success: function(data) {
            console.log("succesfully logged in");
            console.log("access token: " + data.access_token);
        },
        error: function() {
            console.log("authentication failure");
        }
    });
    

If successful, you'll get the access token in the access_token property of the response data. You can then use this to initialize the Simperium instance. You can also use the above code to create a user, just change the url endpoint to /create/ instead of /authorize/.


See the API reference for Simperium.js for more details.