It’s not uncommon to want to assign a single arbitrary variable to a display object. For example, you might want to create a row of buttons that, on click, show a specific image. Some developers will use a dynamic class (like MovieClip) and attach a reference to the image directly to the button (bad); more experienced developers might subclass Sprite and give it a single public variable to reference the image (better, and probably ‘better-practice’) than what I’m about to offer.

For those that don’t know, a Dictionary is a wonderfully handy class that acts just like an object, but instead of having it’s keys set as strings (like Object objects), a Dictionary’s keys can be a reference to any other object. This is extremely useful and extremely under-used. You can manage a great deal of information with a single Dictionary instance.

Using the example mentioned above, you could do something as simple as:

var map:Dictionary = new Dictionary();
var button:Sprite = // some button element
var image:Loader = // some loaded image
map[button] = image;

and later access the image that’s associate with that button:


if you had a dozen button:image pairs, and each button was in Sprite called “buttonRow”, each image in a Sprite called “imageContainer”, you’d need only a single event handler and one Dictionary instance to manage display state:

function showImage(event:MouseEvent):void{
  while(imageContainer.numChildren) imageContainer.removeChildAt(0);
buttonRow.addEventListener(MouseEvent.CLICK, showImage, false, 0, true);