Skip to content

Instantly share code, notes, and snippets.

@LulzAugusto
Created June 27, 2014 23:49
Show Gist options
  • Select an option

  • Save LulzAugusto/608beeb88c4ee80ad1a2 to your computer and use it in GitHub Desktop.

Select an option

Save LulzAugusto/608beeb88c4ee80ad1a2 to your computer and use it in GitHub Desktop.
Messages
var Messages = (function($) {
var Messages = {};
Messages.showMessage = function (type, message) {
showMessage(type, message, containers.pageContainer, arguments);
};
Messages.showModalMessage = function (type, message) {
showMessage(type, message, containers.modalContainer, arguments);
};
Messages.removeMessage = function (type) {
removeMessage(type, containers.pageContainer, arguments);
};
Messages.removeModalMessage = function (type) {
removeMessage(type, containers.modalContainer, arguments);
};
Messages.removeAllMessages = function () {
containers.pageContainer.html('');
containers.modalContainer.html('');
};
Messages.types = {
error: 'error',
info: 'info',
success: 'success'
};
/* Private vars
============ */
var types = {
error: {
alertType: 'danger',
pId: 'error_message',
div: 'div.alert-danger'
},
info: {
alertType: 'info',
pId: 'info_message',
div: 'div.alert-info'
},
success: {
alertType: 'success',
pId: 'success_message',
div: 'div.alert-success'
}
};
var messageDiv = "<div class='alert alert-dismissable alert-[alert-type]'><button type='button' class='close' data-dismiss='alert'>×</button><p id='[p-id]'></p></div>";
var containers = {
pageContainer: $('#messages_area'),
modalContainer: $('#modal_message_area')
};
/* Private functions
================= */
function showMessage(type, message, container, args) {
var exception = 'You must pass the arguments \'type\' and \'message\'. You may find the available types using Message.types.';
var correctArgsSize = 2;
validateArgs(args, correctArgsSize, exception);
var type = types[type];
if (container.find(type.div).length) {
container.find(type.div + ' > p#' + type.pId).text(message);
container.find(type.div).fadeOut('fast').fadeIn('fast');
} else {
var div = messageDiv.replace('[alert-type]', type.alertType).replace('[p-id]', type.pId);
container.append(div);
container.find(type.div + ' > p#' + type.pId).text(message);
}
}
function removeMessage(type, container, args) {
var exception = 'You must pass the argument \'type\'';
var correctArgsSize = 1;
validateArgs(args, correctArgsSize, exception);
var type = types[type];
if (container.find(type.div).length) {
container.find(type.div).remove();
}
}
function validateArgs(args, length, message) {
if (args.length != length) {
throw message;
} else if (Messages.types[args[0]] === undefined) {
throw 'Type doesn\'t exists. Please use Messages.types to get the available types';
}
return true;
}
return Messages;
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment