Skip to content

Instantly share code, notes, and snippets.

@mwoods79
Created December 14, 2011 18:09
Show Gist options
  • Save mwoods79/1477757 to your computer and use it in GitHub Desktop.
Save mwoods79/1477757 to your computer and use it in GitHub Desktop.
Unobtrusively make backbone always fire 'success' and 'error' events.
var _save = Backbone.Model.prototype.save;
var BaseModel = Backbone.Model.extend({
save: function(attrs, options) {
options || (options = {});
var success = options.success;
var model = this;
// success doesn't have an event so always trigger
options.success = function(resp, status, xhr) {
model.trigger('success', model, resp, xhr);
if (success) success(model, resp, xhr);
};
// error already fires event if no callback is given
// so only modify backbone behavior if we have a
// callback
if (options.error) {
var error = options.error;
options.error = function(model, resp, options) {
model.trigger('error', model, rep, options);
error(model, resp, options);
};
}
_save.call(model, attrs, options);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment