简体   繁体   English

在JavaScript库中使用JSON配置文件

[英]Using JSON config file in javascript library

I using almond.js to implement my javascript library. 我使用almond.js来实现我的JavaScript库。 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: 我创建了config.json文件,其中包含所有“全局”变量并定义了“模型”,该文件将注入其他模块:

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 . 问题是,然后我使用我的“模型”对模块进行了定义,请求仍未完成,并且所有“选项”参数仍未undefined Is any way to implement dependencies that will wait for model initialization or maybe another way to achieve this functionality with almond.js? 有什么方法可以实现将等待模型初始化的依赖项,或者是使用almond.js实现此功能的另一种方法?

Should i replace almond.js by require.js to achieve this functionality? 我应该用require.js代替almond.js来实现此功能吗? If can, how it will looks like? 如果可以,它将是什么样子?

Thanks in advance. 提前致谢。

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(){...}); 更改:我删除了静态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. 现在,所有模型选项都可以从config.json文件中解析出来,并在我运行所有依赖项链时准备就绪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM