Game Development Reference
In-Depth Information
By the time the AssetManager class completely instantiates, the manifest will be ready to use. The next method,
preloadAssets , will be called on the instance of the class and will trigger the loading process (see Listing 9-9).
Listing 9-9. The preloadAssets Method Is Called from the Game to Load all Assets
p.preloadAssets = function () {
createjs.Sound.initializeDefaultPlugins();
this.queue = new createjs.LoadQueue();
this.queue.installPlugin(createjs.Sound);
this.queue.on('progress',this.assetsProgress,this);
this.queue.on('complete',this.assetsLoaded,this);
createjs.Sound.alternateExtensions = ["ogg"];
this.queue.loadManifest(this.loadManifest);
}
The necessary plug-ins are used to properly handle sounds in the preload and to take care of mobile situations
before loading the manifest. Next, the on method is used to listen for events that are dispatched when the load
progress has changed and when it is complete. This addEventListener shortcut was used in Chapters 7 and 8, but its
other useful features have not been examined yet. One of those features is its ability to manage scope.
Managing Scope with the on Method
In Chapter 1, the issue of scope was briefly discussed when we were going over the call function in TweenJS. The
issue is that in JavaScript, it's easy to lose scope of objects within callback functions. In the case of the AssetManager
class that we are currently outlining, the progress and complete event handlers on the load queue will not be in scope
of AssetManager . Instead, the scope will actually be in Window by default. This is a problem because you need to
dispatch events during those updates within the class.
This is where the on method helps. The first two parameters in the on method are identical to addEventListener ,
the type of event to listen for and the callback function to handle it. The third parameter allows you to declare the
scope of the event handler function.
this.queue.on('progress',this.assetsProgress, this );
Now within the assetsProgress function, you will be in scope of this , or in this case, the AssetManager class.
This is set up for the queue's complete event as well. Now you can be assured that when these event handlers fire, you
will still be in scope of the class you are building, and can safely access its instance variables and call on its methods.
Creating and Dispatching Events
With scope under control, the handler functions are created next and are used to dispatch events back to the
application (see Listing 9-10).
Listing 9-10. Dispatching the AssetManager Events
p.assetsProgress = function (e) {
this.loadProgress = e.progress;
this.dispatchEvent(this.ASSETS_PROGRESS);
}
p.assetsLoaded = function (e) {
this.dispatchEvent(this.ASSETS_COMPLETE);
}
 
Search WWH ::




Custom Search