HTML and CSS Reference
In-Depth Information
loadImages has a few interesting parts. The first is the regular expression stored in fileRegex . This
has two capturing groups used to grab the row name and the file number. spriter assumes that each file is in
the format of filenamc00e000.ext where the final 0000 represents the sprite number of the row. This is
a common way files are output when generating a list of images.
The first capturing group of the regular expression (capturing groups are saved values created by surrounding
a portion of the regular expression with parentheses) is as follows:
(.*?)
.* means match any character, but adding a question mark ? to the end means make the matcher nongreedy.
This means it can match any character up until the matching part.
The second capturing group— ([0-9]+) —matches any group of numbers, including 1, 001, and 9999.
Calling String.match(regexp) either returns null if the string doesn't match, or any array of
matches if the regular expression matches. The code in Listing 8-7 stores the result of the regular expression
match in the results variable and pulls the rowName and fileNum values out of the capturing groups.
The second interesting part of the code is the anonymous function inside of the for loop. This pattern, which
you have probably come across before, is known as immediately invoked function expression (IIFE). It's useful
in JavaScript because it creates its own scope that enables you to save a variable for later use in a callback. In
this case, it's used because the onerror callback needs to alert the user to which file was a problem.
Without an IIFE, the following onerror callback
img.onerror = function() {
util.print("Error loading: " + file + "\n"); process.exit(1);
}
would just print out the last value assigned to the file variable, which can lead to massive amounts of con-
fusion. By using an IIFE, the anonymous function creates a closure, which means the file variable is saved.
The onload method is replaced with the aforementioned call to join.add() . The variable join is re-
turned from the method because is it used by spriter to indicate when all the images are loaded.
The main data structure created by loadImages is rows . This is passed in as a parameter, but because
objects in JavaScript are passed by reference, any changes you make to the rows object are available in the
calling method. In this case, the rows object is populated by a data structure that looks something like the fol-
lowing:
{
'sprite_one': [ [ 2, Image ],
[ 1, Image ],
... ],
'sprite_two': [ [ 1, Image ],
[ 2, Image ],
... ]
}
Each key of the object matches an array of entries that links a sprite number to the actual Image object.
These images may or may not be ordered correctly, depending on how the operating system returns the list of
files. (These are not guaranteed to be ordered.)
Search WWH ::




Custom Search