Javascript requireJS 中的全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10199622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:17:01  来源:igfitidea点击:

global variables in requireJS

javascriptjqueryrequirejs

提问by daniel__

Possible Duplicate:
How to load bootstrapped models in Backbone.js while using AMD (require.js)

可能的重复:
如何在使用 AMD (require.js) 时在 Backbone.js 中加载引导模型

This is a simple demo about my problem.

这是一个关于我的问题的简单演示。

I need to access the id_userin main.jsfile. My question is, how to avoid global variables in this situation? It is bad practice use global variables for this purpose?

我需要访问id_userinmain.js文件。我的问题是,在这种情况下如何避免全局变量?为此目的使用全局变量是不好的做法吗?

main.js

主文件

require({
    paths : {
        jQuery : 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min'
    }
});

require([ 'jQuery' ], function() {
       alert(id_user);
    });

index.php

索引.php

<script data-main="js/main" src="js/require.js"></script>

<script type="text/javascript">
function users() {
    id_user = <?php echo $id; ?>
}

users();
</script>

采纳答案by GillesC

There shouldn't be any global variable for such usage in project using requirejs as it is to handle modules and all modules (and their properties/methods) are never declared globally to keep the environment nice and clean. If you need one module to use a variable set in an other module then they should either talk to each other via some API or have that variable set as a property, require the module and get the property that way.

在使用 requirejs 的项目中不应该有任何全局变量用于处理模块,并且所有模块(及其属性/方法)永远不会全局声明以保持环境整洁。如果您需要一个模块使用另一个模块中设置的变量,那么它们应该通过某个 API 相互通信或将该变量设置为属性,需要该模块并以这种方式获取该属性。

But maybe you should ask yourself if you actually need requirejs. If you want to build a proper module based application (which I am not sure you are if you wonder how to pass variable around) then yes, if all you want is to load few files from JS then LazyLoad (http://www.appelsiini.net/projects/lazyload) is probably the answer. Just saying it's worth thinking about depending on your case specially considering the footprint of requirejs.

但也许你应该问问自己是否真的需要 requirejs。如果你想构建一个合适的基于模块的应用程序(我不确定你是否想知道如何传递变量)那么是的,如果你只想从 JS 加载几个文件,那么 LazyLoad (http://www. appelsiini.net/projects/lazyload) 可能就是答案。只是说值得根据您的情况考虑,特别是考虑到requirejs的足迹。

回答by dlrust

What you are looking for is the ability to bootstrap config variables into your project. This answers your question

您正在寻找的是能够将配置变量引导到您的项目中。这回答了你的问题

How to load bootstrapped models in Backbone.js while using AMD (require.js)

使用 AMD (require.js) 时如何在 Backbone.js 中加载引导模型