I’m using JavascriptMVC (you don’t need to know it!) and their library “steal” that manages file dependencies.
I’m a beginner with javascript and there’s something I don’t get with namespaces; I need some global variables intialized by PHP, these variables will be used in a lot of other JS files, that’s why I want to make them global:
index.php
<script type="text/javascript">
steal('jquery', function() {
// here is some jquery specific code
var appletVersion = '<?php echo $appletVersion; ?>';
var baseUrl = '<?php echo BASE_URL; ?>';
});
</script>
In my JS files, I can’t access these two variables since I’ve put steal(‘jquery’, function(){ … }); and I guess they are unvisible outside of that block.
test.js
steal('jquery', function(){
console.log(baseUrl); // error
});
That’s because your two variables are local to your function that is passed to steal. My suggestion is to always refer to globals as
window.globalNameto make your intention clear.Note that there is no need to wait for steal to grab jQuery to initialize those variables, so you could do that outside (at the global scope level).
Namespaces
An even better solution than using
window.globalNameis to create your own namespace at the global level so that you can restrict your global namespace pollution to a single object. This will help when debugging since all your code will not be mixed with the rest of the properties on the global object. Just console.log it, and you’ll have all your own globals to look at.Printing PHP values in JS
When you have a value in PHP and you want to print it on the page as a JS variable, you should use
json_encode. Then you won’t have problems with if your string has embedded newlines, quotes or even binary data. You don’t even have to worry about the type,json_encodeoutputs something that is always valid to be used in JavaScript