Wednesday, January 21, 2009

flex: Dictionary Class

Today I was introduced to Dictionaries. No, not the kind that you look up the definitions of words, the Flex code kind. The Class. I was having trouble with this Grid that I am working on, the labels are hard coded in the grid (because of formatting and ordering requirements), and there could be anywhere from 1 to 8 data values that go along with that label. At first I had ArrayCollections with a name property (the label) and the values of each data point, and then I was using methods with return values to get the value I wanted back by looping through the ArrayCollection and looking for the name. This seemed really heavy. I asked a co-worker who is more versed in ActionScript than I am, and he told me about dictionaries. With these you can look up an object via another object rather than an index.

Here are some code snips!

First declare your dictionary object!

private var myDict:Dictionary = new Dictionary();

Then, in a method or event somewhere, populate the Dictionary object with the data. (note - if you're populating the data in the same place, then do it on a preInitialize method).

private function preInit():void
myDict["banana"] = {w:2.5, h:8, color:'yellow'};
myDict["apple"] = {w:3.5, h:3.5, color:'red'};
myDict["orange"] = {w:3, h:3, color:'orange'};

And to use it.

trace( myDict["apple"].color );
//This will output: red

No comments: