Making Backbone.js Work with

Series Overview
<< A Proxy Server for                  Working with Backbone.js and the proxy >>

In the previous post, I showed how you can create a minimal server that proxies requests on to for back-end data storage.

Next, I need to consider the Backbone.js side of things.  Backbone gives a really great way of describing models and collections as long as the data conforms to its REST flavor.  Unfortunately, does things a little bit differently.  I have encapsulated this code into some base prototypes that can be used later.

class Backbone.ParseCollection extends Backbone.Collection
  parse: (resp, xhr) ->
    data = super

  fetch: (options) ->
    if options?.query? = "where=" + JSON.stringify options.query
      delete options.query

class Backbone.ParseModel extends Backbone.Model
  setId: (data) -> = data.objectId unless

  constructor: (model) ->
    @setId model

  parse: (resp, xhr) ->
    @setId super

  toJSON: () ->
    result = super
    delete result.createdAt
    delete result.updatedAt

These base classes help me to adapt the data and behavior of

Collection Fetching

Backbone wants a JSON array from the server. gives you a JSON object with an array called “results” inside the root object.  The code overrides Backbone.Collection.parse to return the array property from the response.

Collection Queries

You can make server-side queries via the query parameters in the API.  The code overrides Backbone.Collection.fetch to take a “query” option.  Mutate it to the format that wants in the API.  I’ll discuss this more in the next post.

Model IDs IDs have the name of “objectId” but Backbone expects the IDs to be named “id”.  The code overrides the Backbone.Model.parse and Backbone.Model.constructor functions to set the ID based on the “objectID” that comes from  This will be used later when updating or deleting the object.

Model Metadata includes two metadata fields: “createdAt” and “updatedAt”.  While they may be useful, fails if you send these fields via a PUT request.  The code overrides Backbone.Model.toJSON to remove these items from the serialization, thus keeping them from being sent to as well.

We now have base prototypes that allow us to communicate with the server.  Instead of extending Backbone.Model and Backbone.Collection, you should make your models extend Backbone.ParseModel and Backbone.ParseCollection. 

In the next post, I will show how to do this and we will play in the browser a bit in order to show how Backbone.js models and collections interact with the proxy server.

Tags: , , , , , , ,

4 Responses to “Making Backbone.js Work with”

  1. [...] Going (Mostly) Server-less with Backbone.js Making Backbone.js Work with [...]

  2. [...] I showed how to create a proxy to use as your data store.  I also showed how to modify Backbone.js to use  Now, I will show how easy it is to use Backbone.js models and collections with a service [...]

Leave a Reply