Backbone fetch cache

by Andy Appleton

Building a Backbone application which interacts with an external API means a lot of calls to model.fetch() and collection.fetch(). This can be pretty inefficient especially if the API does not set cache headers on responses.

Backbone fetch cache is a Backbone plugin which overrides the fetch method on Backbone models and collections to implement caching. Just include the script on your page and start calling fetch with cache: true in the options:

// Return cached data if available, otherwise make an AJAX request
myModel.fetch({ cache: true });

By default responses are cached in memory under Backbone.fetchCache._cache and also persisted to localStorage if available. This can be disabled by setting:

// Cache in memory but not localStorage
Backbone.fetchCache.localStorage = false;

Cached items are saved for 5 minutes by default, but this is also configurable by passing an expires option with a value in seconds to the fetch call:

// Expire this value in 1 minute
myModel.fetch({ cache: true, expires: 60 })

All options are passed through to the actual fetch call so you can still register success and error callbacks for actual AJAX requests. A promise is returned from the fake fetch method so the method signature should be identical whether the data comes from a cache hit or miss.

The code is all available on GitHub along with a full set of tests.