Skip to content

Instantly share code, notes, and snippets.

@Rich-Harris
Created November 11, 2014 23:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rich-Harris/b1a226d12e33c11c848c to your computer and use it in GitHub Desktop.
Save Rich-Harris/b1a226d12e33c11c848c to your computer and use it in GitHub Desktop.
Ractive + AJAX

Since Ractive is solely concerned with rendering UI (like React), it doesn't have any opinions about where its data comes from and goes to. In theory this makes it ultra-flexible (want to use WebSockets? Fine. Want to use the Backbone adaptor? Also fine) but in practice we could probably do a much better job of coming up with some decent patterns and creating tutorials out of them, since this is a question that comes up often.

It's totally possible to just use jQuery (or AJAX lib of your choice), and do this sort of thing:

var updating;

getJSON(endpoint + '/' + id + '.json').then(function (data) {
  if (updating) return; // prevent infinite loops!
  
  updating = true;
  ractive.set('users.' + id, data); // or whatever
  updating = false;
});

// normally the function signature for observers is (newData, oldData, keypath),
// but if you have wildcards then it's (n, o, k, w1, w2, w3...)
ractive.observe('users.*', function (newData, oldData, keypath, id) {
  if (updating) return;
  
  putJSON(endpoint + '/' + id + '.json', newData);
});

If you had a component per model, you could happily bake the logic right into the component:

var User = Ractive.extend({
  oninit: function () {
    this.load();
    this.on('change', this.save);
  },
  load: function () {...},
  save: function () {...}
});

But the honest truth is that I don't know how well these approaches scale, because the vast majority of the stuff I build runs off static files. People on the mailing list might have more of an opinion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment