Skip to content

Instantly share code, notes, and snippets.

@martindrapeau
Created July 23, 2014 14:32
Show Gist options
  • Select an option

  • Save martindrapeau/62a221284491bc11bc9b to your computer and use it in GitHub Desktop.

Select an option

Save martindrapeau/62a221284491bc11bc9b to your computer and use it in GitHub Desktop.
// Subclass the Backbone model to keep the model and its state (errors)
// sent back by the server. Creates a new errorModel property holding
// a Backbone model with errors, mapped to the model attributes.
Backbone.ModelWithState = Backbone.Model.extend({
errorModel: undefined,
constructor: function(attributes, options) {
Backbone.Model.apply(this, arguments);
options || (options = {});
this.errorModel = options.errorModel || new Backbone.Model();
},
save: function(key, val, options) {
if (key === undefined) key = null;
if (key == null || typeof key === 'object') options = val;
options || (options = {});
this.errorModel.clear();
var error = options.error;
options.error = function(model, resp, options) {
if (resp && resp.responseJSON && _.isObject(resp.responseJSON))
model.errorModel.set(resp.responseJSON);
if (error) error(model, resp, options);
};
if (key == null || typeof key === 'object')
return Backbone.Model.prototype.save.call(this, key, options);
else
return Backbone.Model.prototype.save.call(this, key, val, options);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment