Archive for December, 2011

New Bocoup Blog Post: Backbone.js Live Collections

December 26th, 2011  |  Published in Uncategorized

At: http://weblog.bocoup.com/backbone-live-collections

This article introduces a way to incorporate a live data stream into your application using Backbone.js collections. It discusses traditional approaches to connecting to live data, polling and creating a reusable Streaming constructor.

A Backbone collection can be filled in several ways:

  1. By individually fetching or creating models and then adding them to the collection. In this situation, the collection is not responsible for any interaction with a server.
  2. By fetching a group of models using a single request made by the collection object itself. In this situation we define a url property on the collection and fetch it when we’re ready for the data.

When your collection is actually responsible for communicating with an API endpoint to fetch its models, there are several types of data that you might be interested in fetching. For example:

  1. You might have a finite set of data that you need to fetch once for your application.
  2. You might have a feed of data that is constantly updating and thus your collection periodically check for updates.

Dealing with the first scenario is quite simple. It would require defining a Collection constructor that has a url property. Calling fetch on an instance of that collection would then fetch the data and that would be sufficient.

Dealing with the second scenario is somewhat more complex for several reasons:

  1. The end point needs to be queried periodically rather than just once.
  2. The data coming back may already be in your collection (because not enough new data was generated on the server and thus the subset returned is mostly identical.)
  3. The existing collection may need to be ammended or added to.
  4. Some UI component may want to update based on new data being retrieved, but only if there is new data.

Read more here…