Reputation: 101
Suppose I have two javascript files:
The content of Master.js
is this:
<script src="child.js"></script>
<script>
var GlobalVariables = {
'baseUrl": "localhost"
};
$(document).ready(function() {
Child.initialize(true);
});
</script>
as you cans see the Master.js
file load the Child.js
file and also create a GlobalVariables
which I need to use in Child
.
This is what I done so far in Child.js
:
window.Child = window.Child || {};
(function (exports){
"use strict";
exports.GlobalVariables= {};
exports.initialize = function (bindEventHandlers) {
bindEventHandlers = bindEventHandlers || true;
exports.GlobalVariables= GlobalVariables;
}
var label = $('#someLabel').html(GlobalVariables.baseUrl);
I defined the variable GlobalVariables
also using exports.
, but I can access to it using GlobalVariables.baseUrl
only in the initialize
function, in the label
I get:
Uncaught ReferenceError: GlobalVariables is not defined
What I did wrong?
UPDATE
Ok, thanks to @Quentin answer I was able to apply the following edit to my code:
exports.initialize = function (bindEventHandlers) {
bindEventHandlers = bindEventHandlers || true;
if (bindEventHandlers) {
_bindEventHandlers();
}
}
function _bindEventHandlers() {
var label = $('#someLabel').html(GlobalVariables.baseUrl);
}
Upvotes: 1
Views: 28
Reputation: 943939
In child.js you attempt to read the value of GlobalVariables
then in your inline script, you declare GlobalVariables
and give it a value.
You have to declare the variable before you can read from it.
Upvotes: 1