Wednesday, 28 August 2013

Data object with different language options. Javascript implementation

Data object with different language options. Javascript implementation

I have this weird case when I have to manage a few small texts depending
on page language using javascript. Just imagine you need to replace some
parts of the template depending on html lang attribute. So I created
multidimensional data object and decided to go with the following way
around it. Everything works fine but I feel like it is not the best
practice and maybe I could avoid using switch:
jsbin version: http://jsbin.com/EvEciVa/2/
$(function(){
var lang = $('html').attr('lang'),
text;
var obj = {
'en' : {
'title' : 'Title english',
'url' : 'en.html'
},
'fr' : {
'title' : 'Title french',
'url' : 'fr.html',
}
};
switch(lang){
case'fr':
text = [obj.fr.title,obj.fr.url];
break;
default:
text = [obj.en.title,obj.en.url];
}
$('body').prepend('<a href="'+text[1]+'">'+text[0]+'</a>');
});
The question is: As far as I have the lang attribute value (the language),
maybe I could avoid using switch and duplicate cases, instead I could
implement the lang value as variable to access data object, something like
this [obj.lang.title,obj.lang.url]; Of course it wont work in my case.
I would appreciate any opinion. Thank you.

No comments:

Post a Comment