Reputation: 5109
I feel silly but I can't find a good example of how to do this. I've seen some that come close and maybe they are right on target but I can't figure it out.
I'm creating a small application that contains about 6 variables that must have a global scope to my application. Can someone please show me an example?
Global variables:
var scene = viewer.scene;
var ellipsoid = scene.globe.ellipsoid;
var entity;
var newPolygon;
var newOutline;
var canvas = document.getElementById("canvas");
var gl = canvas.getContext("webgl");
var extensions = gl.getSupportedExtensions();
I have the above in a file called globals.js
<script src="Source/globals.js"></script>
<script src="Source/index.js"></script>
<script src="Source/positionHandler.js"></script>
<script src="Source/polyCreate.js"></script>
<script src="Source/polyUpdate.js"></script>
It is listed in the html file. All appears to work just fine but there is a browser level variable that thinks it's false. So now I want to be sure global variables are accessible as expected.
Globals = {
scene: require('scene'),
ellipsoid: require('ellipsoid'),
canvas: require('canvas')
};
module.exports = Common;
or
Globals = {
scene: require('viewer.scene'),
ellipsoid: require('scene.globe.ellipsoid'),
canvas: require('document.getElementById("canvas")')
};
module.exports = Common;
or
Globals = {
scene : viewer.scene,
ellipsoid : scene.globe.ellipsoid,
canvas : document.getElementById("canvas"),
gl : canvas.getContext("webgl"),
extensions : gl.getSupportedExtensions()
};
module.exports = Common;
I don't get the require and how to set it up.
Upvotes: 2
Views: 2104
Reputation: 482
This is kinda complex in JavaScript land, and depends on what context you are speaking about. I assume you are talking about code that runs in the browser (vs node), If this is the case, the simplest way would be to use a name spacing object. and imply import it before other code that replies on it.
for example, you could make the file globals.js
which contains :
MyAppGlobals = { property1: "some-value", anotherProperty2: "other-value" };
In the html just make sure that <script src="path/to/globals.js"></script>
is added before any code that depends on the globals.
if you want a more structured approach, check out projects like webpack. They are great, but a little complex to set up.
Basically webpack or browserify let you write proper import and export statements (the way you can in node.js) and then preforms a dependency analysis and "compiles" all the needed code into a bundle file which you would then include in your html. (sort of a rough description but I hope it helps)
Upvotes: 1
Reputation: 1067
In the browser any variable declared outside of a function scope will be a global var (set on the window object). Make sure that your '< script >' tags are in the correct order (declare your globals before you try to access them).
Upvotes: 2