Jump to content

Managing multiple js files?


Crunchtime
 Share

Recommended Posts

So I sat down and played with some sample code tonight, and loved how quickly I was able to stand everything up. Then I decided I was going to start pulling out my code into separate files and dynamically manage my dependencies. I've used require.js to do that before, but I'm having some trouble with the following basic code:

 

var myGame = new Game(this, 'game', 840, 400, init, create, update);function init() {    myGame.loader.addImageFile('track', 'assets/games/f1/track.png');    myGame.loader.addImageFile('car', 'assets/games/f1/car1.png');    myGame.loader.load();}

 

 

When I run it using the sample code, it works great. When I try to plug it into require.js defines block, it fails because inside init(), myGame is not yet defined. (Because init is called during the constructor of a Game object.)

 

I am trying to wrap my head around why this even works for the basic case provided in the demos. If Game will call init during construction, how in the world can init use the myGame variable? (Since the constructor hasn't returned anything, so myGame is undefined.)

 

 

Link to comment
Share on other sites

When you create a new Game object what it does is just store those function references (init, create, update) internally. Then it does a DOM check. Once the DOM is fully booted/available only then will it call the init function, by which time myGame does exist quite happily.

 

There is another way of doing it - you don't have to pass the default functions at all. Leave them blank and then check on DOM progress yourself. Once done you could use Game.setCallbacks() to set them up, followed by Game.startState() to kick them all off.

 

Alternatively, and perhaps this might be easier, you could use the State approach instead. If you look inside the Tests/states folder you'll find a pure JS example. I think this may be a better solution for your approach.

Link to comment
Share on other sites

Crunchtime: the call of the callbacks is deferred with a timeout. So the object has already been returned from the constructor and is thus accessable from within the init function.

A bit strange pattern, but well...

Link to comment
Share on other sites

Technically it's not a timeout, it's a Dom ready status event, otherwise you can't do things like listen for mouse events, load assets, insert the canvas, etc. so only once the Dom is ready is it safe to call init (by which time myGame is a safe variable to access)

Needless to say if the Dom is already available then init is called immediately.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...