Thursday, March 31, 2011

Flex repeaters tutorial

Flex Repeaters can save you a lot of time. As long as they work, but troubleshooting these little guys can be a serious pain in the butt. In this article I'm going to talk about some best practices to avoid some major headaches.
What is a repeater?
A Flex Repeater is basically a loop function in mxml. You give the repeater a data provider (A collection of data), and the repeater will iterate over that collection and display the MXML components within the repeater.
Simple example:


<VBox>
 <mx:Repeater id="schoolsRpt" dataProvider="{schoolsList}" recycleChildren="true">
  <mx:Text text="{School(schoolsRpt.currentItem).schoolName}"/>
 </mx:Repeater>
</VBox>
 
dataProvider. In this example, we are assuming we have some sort of collection with the name "schoolsList". This can be an an Array, an ArrayCollection, an ICollectionView, an IList, or an XMLList. The dataProvider isn't picky.
recycleChildren. This can cause problems. If you are experiencing buggy behavior; try changing this to false. Repeaters will automatically listen to changes in your dataProvider and update the repeated elements accordingly. Having recycleChildren be "true" can improve performance because after a data change, elements that haven't changed will not get re-created.
schoolsRpt.currentItem. This is the current item within the iteration. So if our dataProvider is an ArrayCollection of School objects, currentItem is the current School object.
There are two things to pay attention to about this. Firstly, since currentItem is just a generic Object, we want to cast it to what we know it to actually be. In my example we are doing that like so: School(schoolsRpt.currentItem). Secondly, currentItem is only available at the time of iteration. If you have an event handler, such as a click event. currentItem is no longer there, so you must use getRepeaterItem()
Example:


<VBox>
 <mx:Repeater id="schoolsRpt" dataProvider="{schoolsList}" recycleChildren="true">
  <mx:Button 
   text="{School(schoolsRpt.currentItem).schoolName}" 
   click="var btn:Button = Button(event.currentTarget); Alert.show(School(btn.getRepeaterItem()).schoolName + ' pressed')"/>
  />
 </mx:Repeater>
</VBox>

No comments:

Post a Comment