Message Property Like functionality in Javascript

In my last project I was using JavaScript heavily which was using messages extensively.

Repetition of same kind of messages from multiple places was becoming unmanageable to handle that I have written a JavaScript class which provides Text message with respect to the message code provided.

This function works in two ways:
1. With code only (Messages.getText("error.text"))
2. With code and args (Messages.getText("error.invalid",args))
Here args is replacement for place holders like:
error.invalid = "Invalid input [1] for [0]"
So Invalid error message can be reused for multiple places where [1] will replace by value and [0] wil be replaced for Field name

For function overloading I have used addMethod - By John Resig as reference


function addMethod(object, name, fn){
var old = object[ name ];
if ( old )
object[ name ] = function(){
if ( fn.length == arguments.length )
return fn.apply( this, arguments );
else if ( typeof old == 'function' )
return old.apply( this, arguments );
};
else
object[ name ] = fn;
}

function MessageProvider() {
this.msg = new Object();
this.msg['error.Login'] = 'Please login to submit link';
this.msg['error.invalid'] = 'Invalid input [1] for [0] [0] is invalid';

addMethod(this, "getText", function(code){
return this.msg[code];
});
addMethod(this, "getText", function(code,args){
var text = this.msg[code];
for (var i = 0; i < args.length; i++) {
var re = new RegExp('\\[' + i + '\\]', 'g');
var dest = args[i];
//text = oldtext.replace(re,'’);
text = text.replace(re,dest);
}
return text;

});

}

var Messages = new MessageProvider();


Now to use centralized messaging in javascript you need to add this code to .js File and include in your html
Add all your messages to msg Object

like :



0 comments: