From 160f0ba9dabefc093b67e83ebb380f18dd55a367 Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Mon, 29 Nov 2010 13:33:07 -0500 Subject: [PATCH] first draft of REST-failure 'error' events. --- backbone.js | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/backbone.js b/backbone.js index a8fbefef..4ca830a7 100644 --- a/backbone.js +++ b/backbone.js @@ -245,7 +245,7 @@ if (!model.set(model.parse(resp), options)) return false; if (options.success) options.success(model, resp); }; - var error = options.error && _.bind(options.error, null, model); + var error = wrapError(options.error, model); (this.sync || Backbone.sync)('read', this, success, error); return this; }, @@ -261,7 +261,7 @@ if (!model.set(model.parse(resp), options)) return false; if (options.success) options.success(model, resp); }; - var error = options.error && _.bind(options.error, null, model); + var error = wrapError(options.error, model); var method = this.isNew() ? 'create' : 'update'; (this.sync || Backbone.sync)(method, this, success, error); return this; @@ -276,7 +276,7 @@ if (model.collection) model.collection.remove(model); if (options.success) options.success(model, resp); }; - var error = options.error && _.bind(options.error, null, model); + var error = wrapError(options.error, model); (this.sync || Backbone.sync)('delete', this, success, error); return this; }, @@ -483,7 +483,7 @@ collection.refresh(collection.parse(resp)); if (options.success) options.success(collection, resp); }; - var error = options.error && _.bind(options.error, null, collection); + var error = wrapError(options.error, collection); (this.sync || Backbone.sync)('read', this, success, error); return this; }, @@ -993,6 +993,17 @@ return _.isFunction(object.url) ? object.url() : object.url; }; + // Wrap an optional error callback with a fallback error event. + var wrapError = function(onError, model) { + return function(resp) { + if (onError) { + onError(model, resp); + } else { + model.trigger('error', model, resp); + } + }; + }; + // Helper function to escape a string for HTML rendering. var escapeHTML = function(string) { return string.replace(/&(?!\w+;)/g, '&')