Wednesday, December 12, 2007

Datasets: Using Repeater

We can loop over a data set in MXML using a Repeater component. General syntax for Repeater is:

<mx:Repeater id="myRepeater" dataProvider="{someColl}"> </mx:Repeater>

It will loop once for each object in the data set. currentItem property is reference data item being processed. currentIndex property is a zero-based counter indicating position of the current item in the data set. But these will be useful only during looping.

After the looping is finished we need to get data from the items that may have been created dynamically inside the Repeater. For this Repeater has getRepeaterItem() method that returns the item in dataProvider property that was used to make the item as an Object type. This can be used on the appropriate event (say click). The code would look like:

<mx:Repeater id="myRepeater" dataProvider="{someColl}"> <mx:RadioButton label="{myRepeater.currentItem.name}" click="someFunc(event.target.getRepeaterItem())"/>
</mx:Repeater>

The properties of the object this obtained can be used as desired.


Another issue is addressing the components created using Repeater. You give an id in the loop. Flex will create an array of the items created by the name of the id. Using the array index individual items may be accessed. The code

<mx:Repeater id="myRepeater" dataProvider="{someColl}"> <mx:RadioButton label="{myRepeater.currentItem.name}" id="myrb" click="someFunc(event.target.getRepeaterItem())"/>
</mx:Repeater>

will create array myrb. Individual information may be accessed using index as
myrb[0].label

TileList control instantiates objects when they are displayed whereas a Repeater inside a Tile container instantiates all the objects in the entire dataset, whether they are initially displayed or not. Depending on size of data, this may delay rendering on the flash player. However scrolling will be better once the page loads in this case as everything is there. If dataset is small, difference will not be noticable. But for bigger sets one has to think and decide.

Q&A

  1. Why would you use a Repeater component?
  2. How can you get data from the items that may have been created dynamically inside a Repeater?
  3. Ho do you address the components created using a Repeater?
  4. What is the alternative to using Repeater?
  5. What is the difference between using a TileList control and a Repeater? How will you decide when to use what?

No comments: