Skip to content

Instantly share code, notes, and snippets.

@bobthecow
Last active December 15, 2015 02:39
Show Gist options
  • Save bobthecow/5189122 to your computer and use it in GitHub Desktop.
Save bobthecow/5189122 to your computer and use it in GitHub Desktop.

This is for RESTful PATCH awesomeness:

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

// sends PATCH {"title": "Current title", "content": "Content", "bonus": 42}
// PATCH just the current title
myModel.patch('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() {
    alert('Whoops!');
  }
});

// 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 this.save(attrs, _.extend({}, options || {}, {patch: true}));
    }
  });
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment