Fork me on GitHub

Browser

Full API doc is available.

NPM

Universal module definition

The whole library is available as a umd (browser global, CommonJS and RequireJS) with name mathsync in the published npm package, at browser/browser.js. It is built using a standalone build with Browserify. For example using a browser global to reference the library and XMLHttpRequest to target the server:

(function (global) {
  var ms = global.mathsync;
  var http = require('http');

  var data = [/* where do your items come from? */];

  var serialize = ms.string.newSerializer(function (item) {
    /* how to serialize your item? */
  });
  var local = ms.array.newSummarizer(data, serialize);

  function fetchSummary(level) {
    var p = new ms.Promise(function (resolve, reject) {
      var req, url = 'http://localhost:4000/api/summary/' + level;
      function ready() {
        if (req.status === 200) {
          resolve(req.responseText);
        } else {
          reject(new Error('Failed to get summary from ' + url));
        }
      }
      function stateChange() {
        if (req.readyState === 4) {
          ready();
        }
      }
      req = new XMLHttpRequest();
      req.onreadystatechange = stateChange;
      req.open('GET', url);
      req.send(null);
    });
    return p.then(JSON.parse);
  }
  var remote = ms.json.newSummarizer(fetchSummary);

  var serialize = ms.string.newSerializer(function (item) {
    /* how to deserialize your item? */
  });
  var resolve = ms.array.newSummarizer(data, remote, serialize, deserialize);
})(this);

and then call it whenever you want to synchronize:

resolve().then(function (difference) {
  difference.removed.forEach(function (i) {
    /* remove deleted item locally! */
  });
  difference.added.forEach(function (i) {
    /* add new item locally! */
  });
});

Using jQuery fetching the JSON can be more concise:

function fetchSummary(level) {
  return ms.Promise.resolve($.getJSON('http://localhost:4000/api/summary/' + level));
}

Browserify

An alternative is to author modules and bundle them using Browserify. Depending on feature modules like generator or streams instead of the global one yields smaller javascript size.