Automatically import an object from the parent class

Right now I am exporting the "singleton" WebGL2RenderingContext as follows:

 export default GLHelper.GetGLContext(UIHelper.Canvas); 

After that, I use it throughout the application, for example:

 import gl from '.'; gl.DrawElements(/*...*/); 

The structure of my project has its root in the class app.ts Inside this class, I have instances of other classes, and basically each class uses the above export.

My problem is that as soon as I decide to use multiple canvas elements, I will have several WebGL2RenderingContext objects, so my singleton export will always work on the same canvas.

The only solution for this case that I can think of is to get all the context objects and pass them as a parameter in the whole code. I am thinking of something like:

 const ctx1 = GLHelper.GetGLContext("id1"); const ctx2 = GLHelper.GetGLContext("id2"); const app1 = new App(ctx1); const app2 = new App(ctx2); 

In the App class, I would need to continue passing the object as follows:

 class App { private _ctx: WebGL2RenderingContext; constructor (ctx: WebGL2RenderingContext) { this._ctx = ctx; // Pass down the context const renderingObj = new Mesh(ctx); } } 

What I would like to achieve is one export in the App class, which will automatically be used in other classes by simply importing it. Thus, I would like renderingObj automatically use the context that was exported to the App instance in which it was created. All this would be really cool if I did not have to pass the context as a parameter.

Is there a way to achieve this or maybe solve the problem differently?

+5
source share
1 answer

Umm, not sure, but I think you can create global variables and then use it wherever you need.

An example of creating a global variable.

 // First declare the window global outside the class declare let window: any; // Inside the required class method let globVarName = window.globVarName; 

EDIT:

What I would like to achieve is one export in the App class, which will automatically be used in other classes simply by importing it.

One option is to use a global variable in the App class to declare it once and use it everywhere, rather than passing the context as a parameter separately in each case.

+2
source

Source: https://habr.com/ru/post/1275470/


All Articles