Patch requests in Backbone

Backbone recently added support for patch requests—great news for developers working with small changes to large data sets. Instead of writing custom serialization every time we need to report a small change, we can now simply send the changed attributes as a patch.

Let’s implement a straight-forward Backbone Model to demonstrate:

var store = new Backbone.Model({
    "name": "The Emporium",
    "inventory": [
      { "id": 1001, "title": "Bronze Pantaloons", "price": 0.99 },
      { "id": 1002, "title": "Silver Pantaloons", "price": 0.99 },
      { "id": 1003, "title": "Brass Pantelettes", "price": 0.99 },
      { "id": 1004, "title": "Big Metal Unit", "price": 1000000.00 }

If someday the store’s name changed, we would want to let the server know.{ name: 'Curiosity Shoppe' });

Compared to, say, changing its inventory, renaming the store is a tiny change. Yet the PUT request generated when we called save will include all of the data attributes within the store.

This is excessive—after all, we only need to change one field. We could define the model in any way we liked (odds are good that we would maintain the inventory data by relationship and omit it when the store is updated), but for the sake of discussion let’s assume that the inventory, title, and any other attributes we might define all make up the same model.

Fortunately for us, Backbone >0.9.9 allows us to use HTTP PATCH requests to save parts of a model rather than the entire thing. Instead of sending along the entire inventory, adding the patch option will save only the specified attributes:{ "name": "a new name" }, { patch: true });

Now only the name will be sent to the server, via a PATCH (if available) or a POST if Backbone.emulateHTTP is set true.

The caveats

Patching model attributes will succeed if two conditions are met. First, the client browser must support the PATCH verb. This is a reasonable assumption for modern browsers (Webkit, Firefox, IE8+); in any case Backbone’s emulateHTTP option will happily replace PATCH with a POST request and an appropriate override header.

Second, the server on the other end of the request must understand and respond to it. The implementation is simple enough, but if it isn’t implemented (or the remote is out of your hands), the request will fail in an unpredictable fashion.