Alpha Hydrae

Coding on the edge of the web...

Backbone Collection 304 Not Modified

I’m using conditional requests with ETags in my latest Rails app to cut down on bandwidth. I noticed that when my Backbone collections got a 304 Not Modified response, they kept being emptied, which is not nice.

After a little research, I found a way to modify them to re-use the same data after receiving a 304.

1
2
3
4
5
6
7
8
9
10
11
12
13
var CustomCollection = Backbone.Collection.extend({

  parse : function(models, options) {

    // Copy previous models array on HTTP 304 Not Modified.
    // The slice call is required to avoid the array being emptied by reference.
    if (options.xhr.status == 304) {
      return this.models.slice();
    }

    return models;
  }
});

Note that the collection will still trigger a reset event with this technique.

Comments