Possible Duplicate:
How to load bootstrapped models in Backbone.js while using AMD (require.js)
This is a simple demo about my problem.
I need to access the id_user
in main.js
file. My question is, how to avoid global variables in this situation? It is bad practice use global variables for this purpose?
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
<script data-main="js/main" src="js/require.js"></script>
<script type="text/javascript">
function users() {
id_user = <?php echo $id; ?>
}
users();
</script>
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.
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.
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)