From 571c54c57ee4e2edd2d493d363c57661b13f872b Mon Sep 17 00:00:00 2001 From: Anatoly Ressin Date: Tue, 28 Apr 2015 17:10:02 +0300 Subject: [PATCH] Align few places in code to match with possible overriding of Backbone.sync Overriding Backbone.sync is a great way to switch a persistence layer. It just lacks two moments that should be overridable too: * Result of `model.save` if model was not validated * Result of `model.destory` if model was new For example if my implementation of Backbone.sync returns promises, then current implementation forces me to check the result before calling '.then()'. With the proposed changes, we will be able to unify `sync` behavior with the rest of the Backbone. @jashkenas ? --- backbone.js | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/backbone.js b/backbone.js index 745d5cb35..33b828d8b 100644 --- a/backbone.js +++ b/backbone.js @@ -586,9 +586,9 @@ // `set(attr).save(null, opts)` with validation. Otherwise, check if // the model will be valid when the attributes, if any, are set. if (attrs && !wait) { - if (!this.set(attrs, options)) return false; + if (!this.set(attrs, options)) return Backbone.notValidated(this); } else { - if (!this._validate(attrs, options)) return false; + if (!this._validate(attrs, options)) return Backbone.notValidated(this); } // Set temporary attributes if `{wait: true}`. @@ -646,7 +646,7 @@ if (this.isNew()) { options.success(); - return false; + return Backbone.newDestroyed(this); } wrapError(this, options); @@ -1366,7 +1366,19 @@ model.trigger('request', model, xhr, options); return xhr; }; + + // Override Backbone.newDestroyed to match with Backbone.sync + // for example to return Promise.resolve(model) + Backbone.newDestroyed = function(model) { + return false; + } + // Override Backbone.notValidated to match with Backbone.sync + // for example to return Promise.reject(model.validationError) + Backbone.notValidated = function(model) { + return false; + } + // Map from CRUD to HTTP for our default `Backbone.sync` implementation. var methodMap = { 'create': 'POST',