freethinker
freethinker

Reputation: 2425

Using JSON config file in javascript library

I using almond.js to implement my javascript library. I trying to separate config variables from code. I created config.json file, which contains all 'global' variables and defined 'Model' which will injected to other modules:

define("Model", [], function () {
    "use strict";

    var model = {
        options: {
        }
    };

    (function () {
        var xhr = new XMLHttpRequest();
        xhr.overrideMimeType("application/json");
        xhr.open('GET', 'Config/config.json', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 300)) {
                model.options = JSON.parse(xhr.response);
            }
        };
        xhr.send();
    })();

    return model;
});

The problem is, then i define over modules which using my 'Model', the request still not finished and all of 'options' parameters is still undefined. Is any way to implement dependencies that will wait for model initialization or maybe another way to achieve this functionality with almond.js?

Should i replace almond.js by require.js to achieve this functionality? If can, how it will looks like?

Thanks in advance.

Upvotes: 1

Views: 482

Answers (1)

freethinker
freethinker

Reputation: 2425

I found solution to my question: Before the changes my launcher script was:

(function () {
    "use strict";
    require("Core");
})();

where "Core" is main module which include all dependencies.

The change: I removed static define("Model", [],function(){...});

My launcher became:

(function () {
    "use strict";
    (function () {
        var xhr = new XMLHttpRequest();
        xhr.overrideMimeType("application/json");
        xhr.open('GET', 'Config/config.json', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 300)) {
                var model = {
                    options: JSON.parse(xhr.response)
                };

                if (define && define.amd) {
                    define("Model", model);
                    require("Core"); 
                }
            }
        };
        xhr.send();
    })();
})();

Now all model options is parsed from config.json file and ready when i run all dependencies chain.

Upvotes: 0

Related Questions