Matthew
Matthew

Reputation: 11270

Namespaces and global variables

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
});

Upvotes: 2

Views: 1839

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92274

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.globalName to make your intention clear.

steal('jquery', function() {
   // here is some jquery specific code
   window.appletVersion = '<?php echo $appletVersion; ?>';
   window.baseUrl = '<?php echo BASE_URL; ?>';
});
// Now you can access window.appletVersion anywhere in your code

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.globalName is 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.

var myNs = {}; // Put all your globals, classes, functions in here to avoid conflicts.
myNs.appletVersion = '<?php echo $appletVersion; ?>' ;

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_encode outputs something that is always valid to be used in JavaScript

myNs.appletVersion = <?php echo json_encode($appletVersion); ?>;
myNs.baseUrl = <?php echo json_encode(BASE_URL); ?>;

Upvotes: 5

Related Questions