December 26th, 2011 | Published in Uncategorized
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:
- 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.
- 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:
- You might have a finite set of data that you need to fetch once for your application.
- 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:
- The end point needs to be queried periodically rather than just once.
- 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.)
- The existing collection may need to be ammended or added to.
- Some UI component may want to update based on new data being retrieved, but only if there is new data.