0

I have switched to modules in JavaScript and now I am experiencing the following issue: I have a helper glutils.js file with a collection of js function. One of the functions looks like this:

function updateGLTexture(texture, format, genMipmaps, data)
{
  gl.bindTexture(gl.TEXTURE_2D, texture);
  //some code  
  gl.bindTexture(gl.TEXTURE_2D, 0);
}

The file is included from the html page like this:

 <!DOCTYPE html>
 <html>
 <head>
 <link rel="shortcut icon" href="#">
 <meta charset="utf-8" />
 <title>Page Title</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <script src="gluitls.js"></script>
 <script type="module" src="webgl_test.js"></script>
 </head>
 <body>
 </body>
 </html>

Inside webgl_test.js I initialize gl context and store it in a global variable:

var gl,canvas  = null;
function init()
{
   canvas = document.createElement('canvas');
   canvas.width = window.innerWidth;
   canvas.height = window.innerHeight;
   document.body.appendChild(canvas);
   gl = canvas.getContext('webgl2', { antialias: false });
   //some more gl related setup and call to:
   //updateGLTexture();
}

Then at some point calling updateGLTexture which uses gl object to access WebGL API but gl is not seen by the scope of the function. It did work before I have switched to modules.What is the elegant way to solve this, without passing gl as a param into the helper functions.

Michael IV
  • 11,016
  • 12
  • 92
  • 223
  • The top level scope of a module is not global scope. It's module scope. The variables declared there are only accessible within that module (although you can export them to make them available to other modules). – T.J. Crowder Oct 04 '22 at 09:36
  • If `updateGLTexture` needs `gl`, it should import it from a module that creates and exports it. (Or they should be in the same module.) – T.J. Crowder Oct 04 '22 at 09:37
  • Guys, please bare with me I am not JS developer )) I need glutils.js know nothing about the module it is used in. This is a generic collection of function. – Michael IV Oct 04 '22 at 09:43
  • 1
    In that case, it should accept `gl` as a parameter rather than relying on a global. You *could* still create `gl` as a global, but it wouldn't be best practice. (You'd do that either by creating it in a non-module, or creating it by assigning to a property of `globalThis`, which creates a global variable: `globalThis.gl = ___`. But I strongly recommend not doing either of those things.) – T.J. Crowder Oct 04 '22 at 09:46

0 Answers0