Question

They examples and the code only mention in passing how to use only the modules you need.

For example, if you need the date formatter, how do you consume it?

Do you just munge it together in the same with globalize.js, or load it somehow separately, similar to loading the cldr files?

For example:

<html>
     <head>
        <script type="text/javascript" src="../js/globalize/globalize.js"></script>
     </head> 
     ...

Loads globalize.js just fine. But I don't have the date module loaded, so somewhere in the code Globalize.dateFormat is not defined.

but if I do this, to get the date module, as shown in one of the examples.

 <html>
     <head>
        <script type="text/javascript" src="../js/globalize/globalize.js"></script>
        <script type="text/javascript" src="../js/globalize/date.js"></script>
     </head> 
     ...

Doesn't load globalize at all; if I try to do Globalize.locale("us") then Globalize is undefined.

Was it helpful?

Solution

There was no need to do a delayed load of date.js, so I specified it in the header in the usual way. I did move it much further down, which may have given some of the prerequisites time to load.

var locLoaded = null;
function loadGlobalize(locale) {
  var loc = util.fixNoE(locale, "en");

  var codes = [
    'ar', 'ca', 'cs', 'da', 'de', 'el', 'en', 'en-001', 'en-AU', 'en-CA',
    'en-GB', 'en-HK', 'en-IN', 'es', 'fi', 'fr', 'he', 'hi', 'hr',
    'hu', 'it', 'ja', 'ko', 'nb', 'nl', 'pl', 'pt', 'pt-PT', 'ro', 'ru',
    'sk', 'sl', 'sr', 'sv', 'th', 'tr', 'uk', 'vi', 'zh', 'zh-Hant'
  ];

  if (codes.indexOf(loc) < 0) {
    var baseLoc = loc.split('-')[0];
    var index = codes.indexOf(baseLoc);
    loc = (index > -1 ? baseLoc : "EN");
  }

  if (loc != locLoaded) {

    var files = [
      "../globalize/supplemental/likelySubtags.json",
      "../globalize/supplemental/timeData.json",
      "../globalize/supplemental/weekData.json",
      "../globalize/main/" + loc + "/ca-gregorian.json",
      "../globalize/main/" + loc + "/numbers.json",
      "../globalize/main/" + loc + "/dateFields.json"
    ];

    var fileCount = files.length;
    files.forEach(function(f) {
      $.getJSON(f, function(data) {
        fileCount--;
        Globalize.load(data);
        if (fileCount == 0) {
          //wait until the last file is loaded to specify the locale
          Globalize.locale(loc);
        }
      });
    });
    locLoaded = loc;
  }
}

loadGlobalize(window.navigator.userLanguage || window.navigator.language);

In my app this code is in block where the DOM and jQuery are already loaded. There are two things that differ from the globalize.js documentation that caused this problem:

  1. You have to do $.getJSON() instead of $.get() as specified in the documentation example.

  2. If you run Globalize.locale() before the appropriate data files are loaded, you don't get a valid date formatter object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top