Add this function after the script you just added in Step 2:
var menu:MovieClip = createEmptyMovieClip("menu", 0);
menu._x = 30;
menu._y = 80;
var i:Number = 0;
for(var city:String in photoData) {
var menuItem:MovieClip = menu.attachMovie("MenuItem", city, i);
menuItem._y = i * (menuItem._height + 2);
menuItem.label.text = city;
menuItem.photos = photoData[city];
menuItem.onRelease = function() {
populatePhotos(this.photos);
}
i++;
}
This script will create our menu from the data defined in Step 2. We first create a container for our menu items and put it in the correct position. This is simply an empty MovieClip named
menu. Then we use a
for...in loop to iterate over the items in our associative array. Each iteration will add an item to our menu by attaching the MenuItem symbol from our library.
Rather than positioning each menu item individually, we will use a container MovieClip and set each item's position relative to the container. Then we simply need to position the container to the desired location on the Stage. In the first line, we create our empty menu container and then we position it by setting its
x and
y properties.
Because this is a
for...in loop we will need to track the number of iterations manually. Before the loop is defined, the script creates a local variable named
i and assigns it the value
0. This variable will be manually incremented each time the loop is iterated.
Note
The letter i is commonly used as the name of an index variable in loops. For nested loops, the letter j is commonly used to define the inner loop's index value.
We are using a
for...in loop because we want to iterate through the keys in our
photoData associative array. Each key value will represent the city name inside our loop.
The first thing we need to do inside our loop is attach the menu item to our menu container. Because this loop dynamically generates the menu items, we need to consider vertical spacing between the items in the menu. We determine this by multiplying the menu item's height by the current iteration count. We also add an additional two pixels for padding.
Inside each of our menu item clips is a text field named
label. Once we have added the item, we will set the label field's text property to the name of the city. The city name is retrieved as the key in our associative array.
Rather than searching through the
photoData object each time we want to retrieve the bitmap photos, we will simply set a reference to these photos inside the menu item instance. So when the item is clicked we can pass that data relative to the menu item.
Finally, we add an
onRelease handler to the menu item. Inside this handler we call the
populatePhotos() function and pass it the reference to the photo data for that city.
Before we end the loop we will increment our index (
i) variable by 1.