Hi guys. I’m sorry if this question has been answered already. Feel free to lay into me if it has.I working on my first big node app and I just feel like I’m doing this wrong. It’s an electron app for managing a football team, and one render process is designed to run during the game. While the game is being played, I have objects that represent each player, each coach, each referee, the stadium, the plays, the stats, etc. Then I have one object that represents the game itself. Sometimes, I need to access one object from another - for example, when I enter a play, it needs to reference player objects to update their stats, then access the game object to change the down and distance, etc.The way I have done it this: each Class is defined and exported in its own module. The exception is the game.js module - it defines the class, but the exports an instance of this class. Within that instance, there are objects that contain all of the other objects (players, coach’s, teams, etc) that I may need.When I launch the program, the game.js module is required and a new Game object is initialized. Then, within each of the other modules where I may need to access the game instance, I require the game.js module and assign a reference of the game object to a global (to the module) variable named ‘game’. Then, when one object needs to access another - say a Play object needs to access a Player object - i just use game.players[{plrId}] and it works the way I want it to.Is the best way to do this. I mean, it works, so why not? It just doesn’t feel right.Two things that make me question it. One, I use the modular-global ‘game’ variable within each instance of the other objects, which just feels odd. I could assign it to this.game, but that would create a circular structure, which I want to avoid.The second, bigger issue, is that I included the var {game}=require(‘./game’) one at the top of every module before the class definition, but I was finding that that didn’t always work. So I had to add a line in the constructor function that checked if game was undefined and if it was, then I would require the file again.TLDRHow do I make an object that can be accessed by multiple modules in a node project? Essentially a global object, though I don’t want to use that word.
Submitted January 27, 2019 at 03:18AM by rudypepper
No comments:
Post a Comment