Posts Tagged ‘ Dictionary ’

DictionaryCollection – a mix between Dictionary and ArrayCollection

Posted in Flex, Quark framework on August 16th, 2010 by bogdan – 2 Comments Tags: , , ,

One day I came across a task which involved using some sort of collection that was bindable
and could store and retrieve data like a dictionary does. And soon I got a new task : to build
such a data type.

Practically I needed a mix between Dictionary and ArrayCollection, so my first idea was to
extend Proxy, in order to access and retrieve data using square brackets, and after that to
create similar methods to ArrayCollection. But after looking over the source code of ArrayCollection,
I’ve noticed it inherits Proxy, due to ListCollectionView inheritance, which saved me from the classic
‘reinventing the wheel’ and led me to improving the wheel instead.

My plan was to modify the methods of ArrayCollection so it adds/removes links to the added/removed
objects and this way they could be retrieved later.It was pretty straightforward to override the methods
and add/remove references to items,which were stored in a Dictionary. It was also easy because I didn’t have to override each method as some of them are reused. For example, addItem  just calls addItemAt.

Besides this basic functionality, I thought it would be useful to add one more feature : adding and
removing references to items based on given properties. Let’s say you add objects with
quantity, price and label properties, using the plain addItem method and you still want to retrieve
them using square brackets. You can do this, but first you have to decide which properties should be
the keys that references to the object. Below is an example for more clarity.

// here I declare an empty DictionaryCollection and set the label property as a key field
var a:DictionaryCollection = new DictionaryCollection(null,"label");
a.addItem({label: "Bread", price: "2", quantity: "1"});
a.addItem({label: "Butter", price: "3", quantity: "2"});
a.addItem({label: "Tea bags", price: "1", quantity: "4"});
a["Jam"] = {label: "Jam", price: "4", quantity: "1"};
// now I can retrieve each object based on its label
trace(a.getItemByKey("Butter").price);   // 3
trace(a["Tea bags"].quantity);             // 4
trace(a["Jam"].label); 			     //	Jam

I hope this code snippet explains pretty well how a DictionaryCollection can be used and you can download it following the link below. I also included the test class for unit testing.

DictionaryCollection

As a conclusion, I’m happy that reading the source code of Flex saved me hours of work and helped me to build a custom data type that should blend seamlessly with the framework.