oxjs/source/Ox/js/Locale.js

91 lines
2.6 KiB
JavaScript
Raw Normal View History

2013-05-09 13:12:26 +00:00
'use strict';
(function() {
var log, translations = {};
2013-05-09 19:20:09 +00:00
/*@
Ox.getLocale <f> Returns locale
() -> <s> Locale (like 'de' or 'fr')
@*/
Ox.getLocale = function() {
return Ox.LOCALE;
};
2013-05-09 13:12:26 +00:00
/*@
Ox.setLocale <f> Sets locale
(locale[, url], callback)
locale <s> Locale (like 'de' or 'fr')
2013-05-09 20:32:50 +00:00
url <s|[s]> one or more URLs of JSON file with additional translations
2013-05-09 13:12:26 +00:00
callback <f> Callback function
success <b> If true, locale has been set
@*/
Ox.setLocale = function(locale, url, callback) {
var isValidLocale = Ox.contains(Object.keys(Ox.LOCALE_NAMES), locale),
urls = [];
2013-05-09 13:12:26 +00:00
if (arguments.length == 2) {
callback = arguments[1];
url = null;
}
if (isValidLocale) {
2013-05-09 13:12:26 +00:00
Ox.LOCALE = locale;
if (locale == 'en') {
translations = {};
} else {
translations = {};
Ox.forEach(Ox.LOCALES, function(locales, module) {
2013-05-09 20:32:50 +00:00
if (
2014-09-26 16:57:12 +00:00
(module == 'Ox' || Ox.load[module])
2013-05-09 20:32:50 +00:00
&& Ox.contains(locales, locale)
) {
urls.push([
2014-09-26 16:57:12 +00:00
Ox.PATH + module + '/json/locale.'
+ locale + '.json'
]);
2013-05-09 13:12:26 +00:00
}
});
}
url && Ox.makeArray(url).forEach(function(value) {
urls.push(Ox.makeArray(value));
});
if (urls.length) {
Ox.getJSON(urls, function(data) {
2013-12-27 10:29:07 +00:00
Ox.forEach(data, function(values, url) {
Ox.extend(translations, values);
});
2013-05-09 16:38:19 +00:00
callback(true);
})
} else {
callback(true);
2013-05-09 13:12:26 +00:00
}
} else {
callback(false);
2013-05-09 13:12:26 +00:00
}
};
/*@
Ox._ <f> Localizes a string
(string[, options]) -> <s> Localized string
string <s> English string
options <o> Options passed to Ox.formatString
@*/
Ox._ = function(value, options) {
var translation = translations[value];
log && log(value, translation);
translation = translation || value || '';
2013-07-22 17:49:50 +00:00
return Ox.formatString(translation, options);
2013-05-09 13:12:26 +00:00
};
/*@
Ox._.log <f> Registers a logging function
(callback) -> <u> undefined
callback <f> Callback function
english <s> English string
translation <s> Translated string
@*/
Ox._.log = function(callback) {
log = callback;
};
2013-05-09 13:03:33 +00:00
})();