jquery - Data object with different language options. Javascript implementation -
i have weird case when have manage few small texts depending on page language using javascript. imagine need replace parts of template depending on html lang attribute. created multidimensional data object , decided go following way around it. works fine feel not best practice , maybe 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: far have lang attribute value (the language), maybe avoid using switch , duplicate cases, instead implement lang value variable access data object, [obj.lang.title,obj.lang.url];
of course wont work in case.
i appreciate opinion. thank you.
to avoid having switch
statement, can set default value this:
var lang = $('html').attr('lang') || 'en';
this means en
default, overridden if there lang
set. can use bracket notation access object this:
$('body').prepend('<a href="' + obj[lang].url + '">' + obj[lang].title + '</a>');
Comments
Post a Comment