Syncing Data with the server

In notebook:
FrontEndMasters BackboneJS
Created at:
2016-06-10
Updated:
2016-06-10
Tags:
JavaScript libraries backend
Collections can have an url property that specifies the RESTful endpoint:
  var Playlist = Backbone.Collection.extend({
    model: SongModel,
    url: '/songs'
});

var dubstep = new Playlist();

dubstep.fetch(); // -> Backbone.sync request to '/songs'

Backbone sync

You can override sync in a model or a collection. 

It's called every time model data is written or read.

If your server implementation doesn't follow REST, then you can override Backbone sync. Like XML, SOAP, or authorisation
  • fetch
  • save
  • destroy
  • create
Everything gets passed through sync in Backbone.
You can always look at the Backbone source code. It's well commented and quite short.
In the source code you can find how to override sync.

Sync Defaults

  • Uses jQuery.ajax
  • RESTful JSON requests

Overriding sync

  • localStorage (to make Backbone use localStorage) - it's used in the example comments application
  • Websockets 
  • whatever you need

jQuery Deferreds

also known as promises (which has become part of the ES6 spec)
jQuery implements the commonJS "Promises A" specification. 
jQuery's implementation can be used synchronously. Creates a list of deferred objects. 
The main concept is that these object go though a state change: from pending to either resolved or rejected.
These deferred objects are part of jQuery AJAX implementation.

They're great because: As long as you have a reference to this deferred object, you can attach handlers even after the state change has occurred.

List of methods:
​always(), done(), fail(), notify(), notifyWith(), pipe(), progress(), promise(), reject(), rejectWith(), resolve(), resolveWith(), state(), then()

​then()​ is the most commonly used
Common use pattern:
  songCollection.fetch().then(function(){
    songCollection.view.render();
})