Skip to content

Instantly share code, notes, and snippets.



Last active Dec 15, 2015
What would you like to do?

This is for RESTful PATCH awesomeness:

var myModel = new Backbone.Model({
  title:   "Current title",
  content: "Content",
  bonus:   42
// PATCH all myModel attributes

// sends PATCH {"title": "Current title", "content": "Content", "bonus": 42}
// PATCH just the current title

// sends PATCH {"title": "Current title"}
// PATCH the current title and content
myModel.patch(['title', 'content']);

// sends PATCH {"title": "Current title", "content": "Content"}
// PATCH with brand new datas
myModel.patch({title: 'New Title!'});

// sends PATCH {"title": "New Title!"}
// triggers a `change` and `change:title` immediately.

.patch() also accepts an options parameter, which is the exact same as the options passed to .save(), e.g. success, error, and wait.

// PATCH with brand new datas and do awesome things
myModel.patch({title: 'Newer Title!'}, {
  wait: true,
  success: function(model) {
    alert('TITL\'d: '+model.get('title'));
  error: function() {

// sends PATCH {"title": "New Title!"}
// triggers a `change` and `change:title` when the response gets back.

The codes:

// backbone.model.patch.js
(function() {
  _.extend(Backbone.Model.prototype, {
    patch: function(key, val, options) {
      var attrs;

      if (_.isArray(key)) {
        // Handle an array of attribute names to PATCH
        attrs   = _.pick(this.attributes, key);
        options = val;
      } else if (key == null || typeof key === 'object') {
        // Handle `{key:value}` -style arguments.
        attrs   = key;
        options = val;
      } else {
        // Handle `"key", value` -style arguments
        (attrs = {})[key] = val;

      return, _.extend({}, options || {}, {patch: true}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.