Cache Jquery Ajax


Here is a very simple approach to caching Jquery ajax calls.

The Model

Here is a simple prototype that will represent out Model and be responsible for making ajax calls.

function MyModel(options) {
	this.url = "";

// cache
MyModel.prototype.cache = {};

// ajax method
MyModel.prototype.all = function (url) {

  // key to uniquely identify ajax call
  var cacheKey = 'all()';

  // check cache?
  if (!this.cache[cacheKey])
  	// add to cache
    this.cache[cacheKey] = $.ajax({
      url: this.url,
      method: 'GET'

  // return promise
  return this.cache[cacheKey];

Notice how we store the jquery promise, which callers will use to fetch data.

Unlike a regular jquery events (binds and triggers) which must be caught right at the moment, a jquery promise can be used at any point after it's completion. This is perfect for caching where subsequent calls will definitely be too late for a triggered event.

The View

Now a prototype that would be responsible for using the model to fetch data and render it somewhere.

function MyView(options) { }

MyView.prototype.renderSomething = function () {
  // construct model
  var model = new MyModel();

  // call method

  	  // add data to MyView = data;

  	  // render here

    }, this)


We simply created the model and used the .done method of the promise to deal with the data right there inline; we could have used a callback as well. Also because we used the jquery proxy, the keyword 'this' still refers to the MyView.