One approach is to find your error handling in the base model that you are extending by assigning a default error handler. This error handler should handle both client and server errors. Here's what the base model extension looks like:
Model = Backbone.Model.extend({ ui: Utils.UI, initialize: function(attributes, options) { options || (options = {}); _.bindAll(this, 'defaultErrorHandler'); this.bind("error", this.defaultErrorHandler); this.init && this.init(attributes, options); }, // Gets call for failures in validate and for server failures. defaultErrorHandler: function(model, error) { var errors; if (_.isArray(error)) { errors = error.join('<br/>'); } else { // Server error; parse as needed into a displayable error. } this.ui.showError(errors); } });
then other models can expand and receive this verification function. Here is a session model that contains client-side validation:
Session = Model.extend({ validate: function(attrs) { var errors = [] if (_.isEmpty(attrs.email)) { errors.push("Email can't be blank"); } if (_.isEmpty(attrs.password)) { errors.push("Password can't be blank"); } return _.any(errors) ? errors : null; } });
You can also handle all this in the validate function, since it is called before saving and after saving, where after saving it can deal with errors that were analyzed from the server response.
Using the approach described above, you should not specify an error function when calling the model save function. It must be handled by basic functionality.
source share