Skip to content

Instantly share code, notes, and snippets.

@masylum
Created January 5, 2012 16:59
Show Gist options
  • Save masylum/1566128 to your computer and use it in GitHub Desktop.
Save masylum/1566128 to your computer and use it in GitHub Desktop.
Errorable
/**
* Errorable
*
* Provides functionality to react when server-side validations fail.
* This module exports 4 methods than you can use on your views.
*
* - onError
* - onSuccess
* - addError
* - removeError
*
* If you want to use this methods on your view just extend the prototype
* by doing:
*
* _.extend(YourView, Teambox.modules.errorable);
*/
(function () {
var Interface = {};
/**
* Default behaviour on a `error` callback after doing a save
*
* @param {Function} callback
* @return {Function}
*/
Interface.onError = function (callback) {
var self = this;
return function (model, response) {
var errors = jQuery.parseJSON(response.responseText).errors;
model.attributes = model.previousAttributes();
self.addErrors('project', errors);
Teambox.helpers.Notifier.post('<p>' + errors.message + '</p>');
if (callback) {
callback(model, response);
}
}
};
/**
* Default behaviour on a `success` callback after doing a save
*
* @param {Function} callback
* @return {Function}
*/
Interface.onSuccess = function (callback) {
var self = this;
return function (model, response) {
self.removeErrors();
if (callback) {
callback(model, response);
}
}
};
/**
* Modify the DOM fields to reflect the given errors
*
* @param {String} model_name
* @param {Object} errors
*/
Interface.addErrors = function (model_name, errors) {
var self = this;
_.each(errors, function (value, key) {
if (['type', 'message'].indexOf(key) === -1) {
self.$('#' + model_name + '_' + key)
.after('<div class="error">' + value[0] + '</div>')
.parent().addClass('has_errors');
}
});
};
/**
* Modify the DOM fields to remove any error
*
* @param {String} model_name
* @param {Object} errors
*/
Interface.removeErrors = function (model_name) {
this.$(model_name + ' .has_errors')
.removeClass('has_errors')
.remove('.error');
};
// exports
App.modules.errorable = Interface;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment