使用AMD require.js&amp ;;定义全局值。 Backbone.js的

时间:2013-08-22 21:01:14

标签: backbone.js requirejs

我正在使用Backbone.js和require.js开发一个前端,一切顺利,直到我需要创建一个名为config.js的文件来存储一些defaule值,以便在整个应用程序中使用它

下面是config.js文件的代码

// Filename: config.js
define([''], function(){        

var baseUrl = "http://localhost:8888/client/",
apiServer = "http://api-server:8888";

return function(type){
    return eval(type);
};

});

在我的一个视图中,我将定义config.js然后我可以访问两者的值

var baseUrl = "http://localhost:8888/client/",
apiServer = "http://api-server:8888";

通过以下代码行,我把它放在我的应用程序的任何* .js文件中

var baseUrl = config('baseUrl');
console.log(baseUrl); //prints out this > http://localhost:8888/client/

这里的问题是我使用eval来获取我需要检索的值的值,我知道这不是安全的方法,但任何人都可以提出安全的解决方案

2 个答案:

答案 0 :(得分:2)

RequireJS允许您定义对象,就像定义更复杂的模块一样。您可以拥有一个配置模块,然后在需要它的任何其他文件中使用它。

在config.js内你可以这样做:

define({
    baseUrl:"http://localhost:8888/client/",
    apiServer:"http://api-server:8888"
});

然后在其他模块中要求它:

//someotherfile.js , defining a module
define(["config"],function(config){
   config.baseUrl;// will return the correct value here
   //whatever
});

旁注:你可以使用实际的全局状态(在窗口上定义变量),但我强烈建议你不要这样做,因为这会使测试变得困难,并且会使依赖隐式而非显式。应始终首选显式依赖项。在上面的代码中,与全局不同,很明显使用它的模块需要配置。

注意,如果您想要的值不是有效的标识符,您也可以使用括号语法config["baseUrl"],这两个(config.baseUrl)在JavaScript中是相同的。

答案 1 :(得分:1)

作为替代解决方案(并且比本杰明更丑陋),您可以将两个网址放入对象中:

define([''], function(){        

    var urls = {
        baseUrl: "http://localhost:8888/client/",
        apiServer: "http://api-server:8888"
    };

    return function(type){
        return urls[type];
    };

});

但是,只需导出一个对象就更清晰了。

相关问题