Last Updated: February 25, 2016
·
1.815K
· crungmungus

Backbone - Force a specific HTTP method when saving

If you're backed into an corner by an unusual RESTful API implementation you can force the method type that the .save method uses when saving a model by passing a 'type' option.

Backbone uses the presence of an id attribute to decide if a model is 'new' or not:

isNew: function() {
    return !this.has(this.idAttribute);
}

When saving, isNew() is used to determine whether to POST or PUT.

var Model = Backbone.Model.extend({
  url : 'http://unusual-api.com/'
});

var m = new Model({
  name : 'test'
});

// No ID attribute so reverts to POST method.
m.save();

// Instead force PUT
m.save(null, {
  type : 'PUT'
});

In this example you could alternatively give your model an arbitrary id as a work around but some APIs don't simply ignore unwanted fields and will throw a validation error. Note: You could alternatively map your idAttribute to some other reliably unique property.

The PATCH method has a more direct shortcut:

// Perform PATCH
m.save({ status : true }, {
  patch : true
});

For obvious reasons this won't work on a new model (a model without an ID). Patch updates are intended for existing entities. But if you're stuck without an ID

// Instead force PATCH
m.save({ status : true }, {
  type : 'PATCH'
});

In every situation where I've had to use this it's not been down to personal choice. There are a lot of different views on what can be considered a RESTful approach as well as a lot of mis-interpretations.