Cover by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Syncing with the Server

By default, whenever you save a model, Backbone will notify your server with an Ajax request, using either the jQuery or Zepto.js library. Backbone achieves this by calling Backbone.sync() before a model is created, updated, or deleted. Backbone will then send off a RESTful JSON request to your server which, if successful, will update the model client side.

To take advantage of this, you need to define a url instance property on your model and have a RESTfully compliant server. Backbone will take care of the rest:

var User = Backbone.Model.extend({
  url: '/users'
});

The url property can either be a string or a function that returns a string. The path can be relative or absolute, but it must return the model’s endpoint.

Backbone maps create, read, update, and delete (CRUD) actions into the following methods:

create → POST   /collection
read   → GET    /collection[/id]
update → PUT    /collection/id
delete → DELETE /collection/id

For example, if you were creating a User instance, Backbone would send off a POST request to /users. Similarly, updating a User instance would send off a PUT request to the endpoint /users/id, where id is the model’s identifier. Backbone expects you to return a JSON hash of the instance’s attributes in response to POST, PUT, and GET requests, which will be used to update the instance.

To save a model to the server, call the model’s save([attrs], [options]) function, optionally passing in a hash of attributes and request options. If the model has an ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required