Статьи

Flex 3: динамические макеты с повторителями

Когда у вас есть статическое количество элементов для отображения, презентация проста. Но что, если это количество является динамическим? Это когда использование повторителя может помочь. Повторитель — это невизуальный компонент, который перебирает коллекцию информации, создавая компоненты на лету по мере продвижения. Одним из наиболее распространенных применений для этого типа функциональности являются динамические формы или каталогоподобные интерфейсы. В таких сценариях база данных запрашивается для получения списка контекстно-релевантной информации, на основе которой генерируется пользовательский интерфейс.

dataProvider крадучий пик

[img_assist | nid = 5753 | title = | desc = | link = url | url = http: //www.manning.com/ahmed/ | align = right | width = 148 | height = 182] DataProvider представляет источник данные; это ссылка (похожая на указатель), где можно найти источник информации. Мы должны кратко представить их здесь, так как они используются для управления повторителями и, следовательно, относятся к следующим примерам. Тип данных, который представляет dataProvider, похож на массив. Хотя у Flex есть массивы, он использует так называемые коллекции для провайдеров данных. Проще говоря, коллекция представляет собой массив стероидов и гораздо больше встроенных возможностей, таких как сортировка и фильтрация.

СОВЕТ
Для вас, ребят из ColdFusion, представьте, что коллекция похожа на массив структур. Java-пользователи могут рассматривать его как ArrayList of Hashmaps.

You can give a dataProvider a plain array and it will work fine, because Flex will wrap a collection around the array behind the scenes. Using the previous tile example, in listing 1 let’s make a collection out of our list of weather icons using a type of collection called an ArrayCollection.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:local="*">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
public var images:ArrayCollection =
new ArrayCollection(
[
{source:"heavyrain.png"},
{source:"partlycloudy.png"},
{source:"sunny.png"},
{source:"thunder.png"},
{source:"cloudy.png"},
{source:"drizzle.png"},
{source:"snow.png"},
{source:"clearnight.png"}
]
);
]]>
</mx:Script>
</mx:Application>

The following is a description of the configurations in listing 1:

  • The collection’s library is imported, enabling us to use it.
  • An instance of an ArrayCollection (a type of collection) is created.
  • The code, [Bindable], informs anyone binding to the variable when changes occur—when changes do occur, the variable prompts whoever is binding to it to respond appropriately, such as updating the display.
  • An ArrayCollection was created using shorthand array notation.
  • Square [ ] brackets are used to indicate an array.
  • Braces { } are used to indicate an object.

Consequently, we’re passing an array of objects. In the real world, we might have queried a database to get this information, and the ArrayCollection would be the query result. Now that we’ve established where the data is coming from, the next step is to know what properties and events are available to connect us into the Repeater.

Properties and events of a Repeater

In order to make effective use of a Repeater we need to know what properties exist, and how they can be applied. Table 1 lists these properties, the most important of which is dataProvider, used to target a source from which to retrieve data.

Table 1 Properties of the Repeater

 Property Type
Description
 id  String  The identifier of the Repeater
 dataProvider  Object  A reference to the data to iterate.
 startingIndex  Number  The index at which to start the loop. Defaults to 0.
 count  Number  Sets the number of loops to conduct. Defaults to the size of the dataProvider.
 currentIndex  Number  Stores the current position in the loop (starting at 0) you can use
to check where in the loop you currently are. This is a read-only property.
 currentItem  Object  A reference to the object to which currentIndex is pointing.
 recycleChildren  Boolean  A performance setting that allows Flex to reuse Child components if possible. Allowed values are true (default) or false.

Table 2 lists a group of events we can use to execute code through the Repeater.

Event
Description
 repeat  Occurs after each iteration of a loop
 repeatStart  Occurs as the Repeater is about to begin looping
 repeatEnd  Occurs after the last iteration is complete

If you make use of events you would need to evaluate properties such as currentIndex and currentItem to learn the status of the properties.

Creating the Repeater

The next thing we need to do is create a Repeater using the <mx:Repeater> tag, and specify the dataProvider we want it to use. Listing 2 shows what this would look like.

<mx:Tile direction="horizontal" >
<mx:Repeater id="myRepeater" dataProvider="{images}">
</mx:Repeater>
</mx:Tile>

The Repeater is inside Tile because we want it to create child objects inside the Tile by looping over the ArrayCollection. Adding what you’ve learned about a Repeater’s properties, the last piece is to add the component that we want created with each iteration—for this example, an Image component. Using the currentItem property we can use the binding mechanism of Flex to get the current image at any point in time:

<mx:Image source="{myRepeater.currentItem.source}"/>

Let’s put this all together in listing 3 and see what the code looks like.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:local="*">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable]
public var images:ArrayCollection =
new ArrayCollection([
{source:"heavyrain.png"},{source:"partlycloudy.png"},
{source:"sunny.png"},{source:"thunder.png"},
{source:"cloudy.png"},{source:"drizzle.png"},
{source:"snow.png"},{source:"clearnight.png"}]);
]]>
</mx:Script>
<mx:Tile direction="horizontal" >
<mx:Repeater id="myRepeater" dataProvider="{images}">
<mx:Image source="{myRepeater.currentItem.source}"/>
</mx:Repeater>
</mx:Tile>
</mx:Application>

The result is shown in figure 1; you can add or remove items to the ArrayCollection, without needing to change the code that handles the output.

[img_assist|nid=5930|title=|desc=|link=none|align=none|width=269|height=273]

Think of a Repeater as a loop statement that iterates over an array. The item in the array to which the iteration is currently pointing is accessible via the Repeater’s currentItem and currentIndex properties.
Generating the display is the major goal of a Repeater, but with Flex there are always events available to react when certain triggers occur.

Working with Repeater events

You can easily tie into the events of a Repeater by specifying what ActionScript you want to execute. In the Repeater, we’re going to specify a couple of event handlers to invoke when these events occur:

<mx:Repeater id="myRepeater" dataProvider="{images}"
repeatStart="handleRepeatStart()"
repeat="handleRepeat()"
repeatEnd="handleRepeatEnd()">

The code for these event handlers looks along the lines of listing 4.

public function handleRepeatStart():void
{
mx.controls.Alert.show("Repeater starting!");
}
public function handleRepeat():void
{
trace("Currently on index:" + myRepeater.currentIndex);
trace("Image is:" + myRepeater.currentItem.source);
}
public function handleRepeatEnd():void
{
mx.controls.Alert.show("Repeater finished!");
}

If you were to run this script, you would see two pop-up alerts for the start and end events, and your output log (listing 5) would have a line item for each image.

Currently on index:0
Image is:heavyrain.png
Currently on index:1
Image is:partlycloudy.png
Currently on index:2
Image is:sunny.png
Currently on index:3
Image is:thunder.png
Currently on index:4
Image is:cloudy.png
Currently on index:5
Image is:drizzle.png
Currently on index:6
Image is:snow.png
Currently on index:7
Image is:clearnight.png

Repeaters are a handy way of generating components from a collection of variable data.

This article is taken from the forthcoming book Flex 3 in Action by Tariq Ahmed with Jon Hirschi, and Faisal Abid, (Manning, 2008). This 545-page easy-to-follow, hands-on tutorial goes beyond feature coverage and helps you put Flex 3 to work in real day-to-day tasks. This article introduces Repeaters: If you need to make components on the fly based on a set of data, you can use a Repeater to generate those for you. For the book’s table of contents, the Author Forum, and other resources, go to http://www.manning.com/ahmed/.