1. Trang chủ
  2. » Công Nghệ Thông Tin

O’Reilly Programming Flex 2 phần 6 pptx

46 331 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Managing State in ActionScript
Trường học University of Information Technology and Communication
Chuyên ngành Computer Programming
Thể loại Lecture notes
Năm xuất bản 2023
Thành phố Hanoi
Định dạng
Số trang 46
Dung lượng 180,17 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

You want to reference the added component before first requesting the state For example, when you create a component with several states, you might want to reference added components via

Trang 1

220 | Chapter 10: Managing State

define the overrides property as an array before you can add overrides to a stateusing ActionScript:

stateA.overrides = new Array( );

Once you’ve defined theoverridesproperty as an array, you can add overrides to thearray:

stateA.overrides.push(exampleAddChild);

Adding and Removing Child Elements

You can add and remove child elements in MXML using the <mx:AddChild> and

<mx:RemoveChild> tags The corresponding ActionScript classes are mx.states AddChild andmx.states.RemoveChild

When you want to add child elements using theAddChildclass, you must first struct a new instance:

con-var addChild:AddChild = new AddChild( );

When using MXML, nest the component tag within the <mx:AddChild>tag Whenusing ActionScript, you must assign a component reference to thetargetproperty oftheAddChild object:

var button:Button = new Button( );

Trang 2

Using ActionScript to Define States | 221

Setting Properties and Styles

To set properties and styles with ActionScript you use the mx.states.SetPropertyandmx.states.SetStyle classes Each class has properties that correspond exactly tothe attributes of the <mx:SetProperty> and <mx:SetStyle>tags Both classes definetarget,name, andvalueproperties To simplify things you can also pass thetarget,name, andvalueto the constructors The following examples illustrate how to use theSetProperty andSetStyle classes:

var setProperty:SetProperty = new SetProperty(button, "width", 200);

var setStyle:SetStyle = new SetStyle(button, "color", 0xFF00FF);

Setting Event Handlers

The mx.states.SetEventHandler class corresponds to the <mx:SetEventHandler> tagfor setting event handlers The class defines target and name properties that corre-spond to the target and name attributes of the<mx:SetEventHandler>tag To makethings even simpler, theSetEventHandler constructor allows you to pass the targetand name parameters:

var setEventHandler:SetEventHandler = new SetEventHandler(button, "click");

When you use the<mx:SetEventHandler>tag, you use thehandlerattribute to specifythe ActionScript to call when the event occurs However, when working with aSetEventHandlerobject, you use thehandlerFunctionproperty ThehandlerFunctionproperty requires a reference to a function/method Flash Player then calls that func-tion/method when the event occurs The following instructs Flash Player to call afunction namedclickHandler when the user clicks the button:

setEventHandler.handlerFunction = clickHandler;

Using Dynamic States

To better understand how to use ActionScript’s dynamic states created at runtime,let’s look at an example Example 10-9 builds a multipage form from XML data andloads it at runtime The form is composed of states for each page

For the purposes of this example, the following XML data is used and saved in a file

called forms.xml.

Example 10-9 forms.xml

<forms>

<form id="1" label="Name">

<item type="textinput" name="firstName" label="First Name" />

<item type="textinput" name="lastName" label="Last Name" />

</form>

<form id="2" label="Address">

<item type="textinput" name="address" label="Street Address" />

<item type="textinput" name="city" label="City" />

Trang 3

222 | Chapter 10: Managing State

To work with the data, you can define several classes: CustomFormItem, CustomForm,andCustomFormManager

TheCustomFormItem class can be used to represent an item from the form An itemcan consist of alabel and a form control such as a text input, text area, or check-box Example 10-10 defines theCustomFormItem class

<item type="textinput" name="state" label="State" />

<item type="textinput" name="postalCode" label="Postal Code" />

</form>

<form id="3" label="Phone and Email">

<item type="textinput" name="phone" label="Phone Number" />

<item type="textinput" name="email" label="Email" />

</form>

<form id="4" label="Address">

<item type="textarea" name="agreement" label="">

Example Corporation reserves all rights.

public class CustomFormItem {

private var _type:String;

private var _label:String;

private var _name:String;

private var _value:String;

public function CustomFormItem(type:String, label:String,

Trang 4

Using ActionScript to Define States | 223

TheCustomForm class (Example 10-11) is essentially a collection of form items withthe addition of a method that constructs a new state based on the form

public function getValue( ):String {

return _value;

}

public static function parseFromXML(xml:XML):CustomFormItem {

var type:String = xml.@type;

var label:String = xml.@label;

var name:String = xml.@itemName;

var value:String = null;

public class CustomForm {

private var _label:String;

private var _items:Array;

public function CustomForm(label:String, items:Array) {

Trang 5

224 | Chapter 10: Managing State

public function getItems( ):Array {

return _items.concat( );

}

public function toState(parent:Grid):State {

var state:State = new State( );

state.overrides = new Array( );

for(i = 0; i < count; i++) {

else if(type == "checkbox") {

component = new CheckBox( );

CheckBox(component).label = item.getLabel( ); }

else if(type == "textarea") {

component = new TextArea( );

component.width = 200;

TextArea(component).text = _items[i].getValue( ); }

Trang 6

Using ActionScript to Define States | 225

TheCustomFormManagerclass (Example 10-12) is a Singleton class that loads the XMLdata and provides an interface to a collection of forms

public static function parseFromXML(xml:XML):CustomForm {

var label:String = xml.@label;

var items:Array = new Array( );

public class CustomFormManager extends EventDispatcher {

private static var _instance:CustomFormManager;

private var _forms:Array;

private var _index:uint;

public function CustomFormManager(enforcer:SingletonEnforcer) {

public function load(url:String):void {

var request:URLRequest = new URLRequest(url);

var loader:URLLoader = new URLLoader( );

Trang 7

226 | Chapter 10: Managing State

The MXML (with embedded ActionScript) in Example 10-13 illustrates how to usethe preceding code to construct dynamic states based on XML data

public function hasNextForm( ):Boolean {

return _index < _forms.length;

_forms = new Array( );

var xml:XML = new XML(event.target.data);

var forms:XMLList = xml.children( );

Trang 8

Using ActionScript to Define States | 227

import mx.states.State;

import com.oreilly.programmingflex.states.CustomForm;

import com.oreilly.programmingflex.states.CustomFormManager;

private var _stateIndex:uint;

private var _stateCount:uint;

private function initializeHandler(event:Event):void {

var formManager:CustomFormManager = CustomFormManager.getInstance( ); formManager.load("forms.xml");

private function nextForm( ):void {

currentState = "form" + ++_stateIndex;

}

private function previousForm( ):void {

currentState = "form" + _stateIndex;

Trang 9

228 | Chapter 10: Managing State

Managing Object Creation Policies (Preloading Objects)

By default, components added by nonbase states aren’t instantiated until the state isfirst requested The MXML in Example 10-14 illustrates this Thetrace( )statementoutputsnull becausebutton is not yet defined when the application first starts

However, you can manage when components added by states are instantiated using acreation policy The default creation policy setting isauto, which means the compo-nent is instantiated when the state is first requested You can set creation policies foreach added component using thecreationPolicyattribute of the<mx:AddChild>tag,

or the creationPolicyproperty of the AddChild class The possible values areauto(default),all, andnone

When you set the creation policy of an added component toall, the component isinstantiated when the application first starts The MXML in Example 10-15illustrates how that works Because the creation policy of the button is now set toall, thetrace( ) statement outputs the reference to the component

Trang 10

Managing Object Creation Policies (Preloading Objects) | 229

When the creation policy is set to none, the component isn’t instantiated until youexplicitly call thecreateInstance( )method of theAddChildobject If you’re definingthe AddChild object using the <mx:AddChild> tag, you must assign an id.Example 10-16 illustrates how the none creation policy works The first trace( )statement outputsnullbecause the component hasn’t been instantiated The secondtrace( )statement outputs the reference to the component because it is called imme-diately following the call tocreateInstance( )

Example 10-15 Understanding object creation policies: policy all

<mx:AddChild creationPolicy="none" id="exampleAddChild">

<mx:Button id="button" label="Example" />

Trang 11

230 | Chapter 10: Managing State

In most applications, the default (auto) creation policy is the correct setting ever, there are several reasons you might want to select a different creation policy.Theall policy, for example, is useful in at least two scenarios:

How-The added component requires a long time to initialize

If the component isn’t initialized until the state is requested, the user mightexperience a delay By setting the policy to all, the component is initializedwhen the application first starts; that should mitigate any issues related to com-ponent initialization times and delays when changing states

You want to reference the added component before first requesting the state

For example, when you create a component with several states, you might want

to reference added components via an accessor method

Thenonepolicy may not seem immediately useful; however, consider that theautoandall policies are very black and white:

• When you select auto, components aren’t instantiated until the state isrequested

• When you select all, components are instantiated when the applicationinitializes

There are reasons you might want to ensure that a component initializes before astate is requested, but you don’t want to force the component to instantiate whenthe application initializes For example, a complex application might contain manystates, each of which has components that take a long time to initialize If you set thecreation policy of all theAddChild objects toall, the user might have to wait a longtime before the application initializes However, it might be a better user experience

if the application starts right away while the components for the rest of the states tialize in the background Using thenonecreation policy allows you to do just that.Simply call thecreateInstance( ) method of theAddChild object to instantiate thechild component

ini-Handling State Events

Four events are associated with state changes:

• When a state change is requested, the application or component containing thestate dispatches acurrentStateChanging event The event occurs before the stateactually changes

• Once the state has changed, the application or component dispatches acurrentStateChanged event Both events are of typemx.events.StateChangeEvent(use the constantsCURRENT_STATE_CHANGINGandCURRENT_STATE_CHANGEDto add lis-teners) Neither event is cancelable, which means you cannot prevent a statechange from occurring by canceling acurrentStateChanging event, for example.Rather, both events are used primarily by the transitions framework to detectwhen a transition should occur

Trang 12

Summary | 231

• TheenterState andexitState events occur when the state starts and stops:

— TheenterState event occurs as soon as the state has started but before it isapplied to the view

— TheexitState event occurs as soon as the state is about to stop

Both events are of typemx.events.FlexEvent (use the constantsENTER_STATEandEXIT_STATE to add listeners)

• TheenterState event is dispatched by aState object when the state starts, and

by an application or component when returning to the base state TheexitStateevent is dispatched by aStateobject when the state stops, and by an application

or component when exiting the base state

When to Use States

States are a powerful and extremely useful feature of the Flex framework You canaccomplish many things using states In fact, you can use states for so many thingsthat it’s possible to use them in ways for which they are not really designed Statesare very closely associated with the view, so they should be used for things that affectthe view or changes in behavior associated with the view (in the case of setting eventhandlers) Although you could easily use states to change data models, for example,it’s not an appropriate use To better understand the most appropriate use of states,consider the following guidelines for when to use them:

For applying a transition effect

If you want to use a transition, you ought to use states

For changing or replacing all or part of a screen

If you’re adding or removing components, states are usually the most ate choice

appropri-There are some gray areas that make states an unlikely choice For example, youmight have a form with a text input control that is disabled until the user selects a

checkbox You could use states for that, but unless you want to apply a transition, it

is probably much more appropriate to simply use ActionScript triggered by theclickevent of the checkbox

Summary

In this chapter, you learned about Flex view states You learned what they are andhow to create them States consist of overrides, which are the parts of a state thatspecify how the state differs from another state Overrides frequently consist ofthings such as adding and removing components as well as setting styles, properties,and event listeners

Trang 13

Chapter 11

CHAPTER 11

Flex applications always consist of one or more user interface and/or container ponents At a minimum, a Flex application has an application container, but usually

com-it has many addcom-itional components Although the default behavior for components is

fairly static, you can liven up an application with the use of effects An effect is an

action that takes place, such as moving, fading, or zooming into or out of a nent An effect can even be a nonvisual behavior, such as playing a sound Usingeffects, you can create applications that are more visually (and audibly) interesting.Perhaps more importantly, you can use effects to direct focus and help users betterunderstand how to use applications

compo-Another way in which you can use effects is to create transitions between states InChapter 10, you learned about creating state views However, so far in the bookyou’ve learned how to create only sudden state changes Using effects as transitions,you can create more interesting and seamless changes between states For example,rather than an added component suddenly appearing, it can fade in Not only doesthis generally create a more visually engaging user experience, but also effects can beused to show emphasis and to highlight change

In this chapter, we’ll look at how to work with effects and transitions We’ll discusshow to trigger effects, how to programmatically control effects, and even how to cre-ate custom effects We’ll also discuss how to use an effect as a transition betweenstates, as well as how to create custom transition types

Using Effects

Effects are actions that you can apply to components Common examples of effectsare fades, moves, and zooms The Flex framework includes many standard effects, asyou’ll see later in Table 11-1 However, you are not limited to using those effectsexclusively You can also create composite effects both in sequence (e.g., fade, thenmove) and in parallel (e.g., fade and move) You can also write custom effects usingActionScript These custom effects can then be used in exactly the same ways asstandard effects

Trang 14

Using Effects | 233

Working with Effects

In order to use an effect you, must first create an instance of the effect There are twobasic ways to create an effect instance: using MXML or using ActionScript We’lllook at each technique

MXML is arguably the most common way to create an effect instance You needmerely to add a tag of the appropriate type and give it an ID You should place thetag as a child of the root document element For example, you can place the tag as achild of an Applicationtag The tag should never be nested within other tags (i.e.,within other child components) The following example creates a new move effectinstance:

<mx:Move id="moveEffect" />

Table 11-1 lists all the standard effects

Each of the effects in Table 11-1 has a different set of properties that you can set tocustomize the effect For example, by default a move effect moves both to and fromthe component’s current location The result is that the effect doesn’t seem to doanything However, you can specify the xFrom, xTo, yFrom, and/or yTo property toaffect how the component will move The following example creates an effect thatmoves the component along the x-axis from –100 to the current x coordinate value:

<mx:Move id="moveEffect" xFrom="-100" />

You can also construct effects using the appropriate constructor as part of a newstatement For example, the following code creates a newMove instance:

private var moveEffect:Move = new Move( );

Table 11-1 Standard effects

Effect Description

Blur Animate a blur.

Move Animate the motion of a component in the x and/or y direction.

Fade Animate the alpha value of a component.

Dissolve Animate the alpha value of a rectangular overlay.

Glow Apply a glow to a component, and animate the appearance/disappearance of the glow.

Resize Animate the width and height of a component.

Rotate Rotate a component.

Zoom Animate the x and y scales of a component.

WipeLeft

WipeRight

WipeUp

WipeDown

Apply a mask that moves to reveal or hide a component.

Iris Apply a mask that scales to hide or reveal a component.

AnimateProperty You can use this effect to animate any numeric property of a component.

Trang 15

234 | Chapter 11: Using Effects and Transitions

Regardless of how you construct the effect instance, you can set the properties usingActionScript:

moveEffect.xFrom = -100;

Playing Effects

There are two ways in which you can play effects: using theplay( )method or using

a trigger We’ll look at theplay( )method first because it is the most straightforwardway to use an effect Then we’ll look at using triggers

Manually playing effects

You can use theplay( )method of an effect to manually play the effect In order for

an effect to play, it must have a target to which it applies the settings For example, ifyou have created a move effect instance that is supposed to move a component from–100 to its current location, you must tell it what component to use as the target.You can accomplish that using thetarget property:

<mx:TextInput id="textInput1" creationComplete="applyEffect(event)" />

<mx:TextInput id="textInput2" creationComplete="applyEffect(event)" />

<mx:TextInput id="textInput3" creationComplete="applyEffect(event)" />

<mx:TextInput id="textInput4" creationComplete="applyEffect(event)" />

</mx:VBox>

</mx:Application>

Trang 16

Using Effects | 235

In this example, the text inputs each appear to slide from the left

You can also specify more than one target at one time for an effect, using thetargetsproperty With thetargetsproperty, you can specify an array of targets to which theeffect should be applied In Example 11-2, the result is visually identical to the pre-ceding code, but this time the effect is played just once rather than four times

It’s also worth noting that you can apply an effect to a container In the case of themove effect applied in the preceding examples, it would be much simpler to applythe effect to theVBox instance, as shown in Example 11-3

Example 11-2 Applying an effect to many targets

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

<mx:Script>

<![CDATA[

private function applyEffect(event:Event):void {

moveEffect.targets = [textInput1, textInput2, textInput3, textInput4];

Trang 17

236 | Chapter 11: Using Effects and Transitions

However, note that this works only when the result of the effect is the same whenapplied to the container as when applied to the child components The precedingexamples have the same visual result because the effect (move) works identically ifapplied to the container or the child components This is not true for all effects; forexample, a rotate effect will have a different result if applied to a container or ifapplied to the child components The code in Example 11-4 applies a rotate effectfirst to the individual child components

<mx:Move id="moveEffect" xFrom="-100" />

<mx:VBox id="vbox" creationComplete="applyEffect(event)">

<mx:VBox id="vbox" x="400" y="400" clipContent="false">

<mx:TextInput id="textInput1" creationComplete="applyEffect(event)" />

<mx:TextInput id="textInput2" creationComplete="applyEffect(event)" />

<mx:TextInput id="textInput3" creationComplete="applyEffect(event)" />

<mx:TextInput id="textInput4" creationComplete="applyEffect(event)" />

</mx:VBox>

</mx:Application>

Example 11-3 Applying an effect to a container (continued)

Trang 18

Using Effects | 237

When applied this way, the individual text inputs rotate independently, each aroundtheir own center point In Example 11-5, we’ll use the same effect, but we’ll apply it

to theVBox instance instead

This change causes the entire container to rotate, rather than each child componentrotating independently

Using triggers

Triggers occur within a Flex application to start an effect Using triggers allows you

to create and apply effects entirely with MXML This is not necessarily better orworse than using theplay( ) method It is just a different way of applying effects

In Flex terminology, a trigger combined with an effect is called a

Trang 19

238 | Chapter 11: Using Effects and Transitions

You can assign an effect instance to the trigger for a component, and the effect will

be applied automatically when that trigger occurs When you use triggers, you donot have to set a target for the effect Instead, the target is automatically set when theeffect is triggered The following example uses triggers to apply a move effect to each

of four text input controls as they are created:

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

<mx:Move id="moveEffect" xFrom="-100" />

<mx:VBox>

<mx:TextInput id="textInput1" creationCompleteEffect="{moveEffect}" /> <mx:TextInput id="textInput2" creationCompleteEffect="{moveEffect}" /> <mx:TextInput id="textInput3" creationCompleteEffect="{moveEffect}" /> <mx:TextInput id="textInput4" creationCompleteEffect="{moveEffect}" /> </mx:VBox>

</mx:Application>

Of course, you can apply effects to containers using triggers as well The followingexample applies the move effect to the container rather than the child components:

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

<mx:Move id="moveEffect" xFrom="-100" />

<mx:VBox creationCompleteEffect="{moveEffect}">

<mx:TextInput id="textInput1" />

Table 11-2 Standard triggers

addedEffect The component was added to the display list.

removedEffect The component was removed from the display list.

creationCompleteEffect The component has been created and initialized.

focusInEffect The component has received focus.

focusOutEffect The focus has moved from the component.

hideEffect The component has been hidden (made not visible).

showEffect The component has been shown (made visible).

rollOverEffect The user has moved the mouse over the component.

rollOutEffect The user has moved the mouse out of the component.

mouseDownEffect The user has pressed the mouse button over the component.

mouseUpEffect The user has released the mouse button over the component.

moveEffect The x and/or y property of the component has changed.

resizeEffect The width and/or height of the component has changed.

Trang 20

typi-if you were using ActionScript However, triggers typically work best for simple uses

of effects When you need to customize how the effect is applied, it can get more ficult to use triggers, and in those cases, it is typically better to use ActionScript

dif-Effect Events

All effects dispatch events that notify listeners when the effects start and when theyend Those events are calledeffectStartandeffectEnd The effect events are of typemx.events.EffectEvent Example 11-6 illustrates how to use the effectEndevent toset the alpha of a container after it has moved from the left

Example 11-6 Listening for an effectEnd event

private function effectEndHandler(event:EffectEvent):void {

// The initial alpha is 5 Once the effect is complete set the alpha to 1.

vbox.alpha = 1;

}

]]>

</mx:Script>

<mx:Move id="moveEffect" xFrom="-100" effectEnd="effectEndHandler(event)" />

<mx:VBox id="vbox" alpha=".5" creationCompleteEffect="{moveEffect}">

Trang 21

240 | Chapter 11: Using Effects and Transitions

The EffectEvent type inherits the standard event properties such as target andcurrentTarget However, effects use factories to create the effect instances, and thetarget property of an EffectEventobject references the factory used to create theeffect, not the effect instance A factory is a programming construct that is responsi-ble for creating objects In this case, aMoveobject (or any other effect type) is a fac-tory that creates the actual instances of the effect that get applied to components Ifyou need to retrieve a reference to the actual effect instance (rather than the factory),you can use theeffectInstanceproperty Example 11-7 illustrates this by reversing amove effect once it has played

The preceding examples illustrate how to add a handler for an event using anattribute Of course, you can also add a handler using ActionScript With Action-Script you use addEventListener as you would normally when registering any lis-tener for any event In that case, you can use the EffectEvent.EFFECT_START andEffectEvent.EFFECT_END constants, as shown here:

Example 11-7 Reversing an effect

Trang 22

Using Effects | 241

Tween is a word carried over from Flash Tween is short for in

between, which refers to an animation technique in which starting and

ending values are given, and the intermediate values are automatically

calculated The result is that an animation (such as a translation, scale,

or rotation) can be achieved quite simply by providing just the

start-ing and endstart-ing values along with a duration.

Tween events are of type mx.events.TweenEvent The tweenStart event occurs as atween begins, which is immediately after theeffectStart event in most cases ThetweenUpdate event occurs for each change to the tweened property or properties.That means that there might be manytweenUpdateevents Then, once a tween effecthas completed, it dispatches atweenEndevent ThetweenEndevent always follows thelasttweenUpdate event and precedes theeffectEnd event

TheTweenEventclass defines avalueproperty in addition to the inherited event erties The value property contains the current value of the property or propertiesbeing changed over time For example, for a rotate effect, the TweenEvent object’svalue property is a number corresponding to the current rotation property of thecomponent being rotated Yet if the effect affects more than one property, thevalueproperty of theTweenEventobject is an array of the values of the affected properties.For example, a move effect animates the x and y properties of a component TheTweenEventdispatched by a move effect has avalueproperty that is an array with twoelements corresponding to the x and y values

prop-Composite Effects

Not only can you create simple effects using the standard effect types, but you alsocan create composite effects by combining them There are two ways you can com-bine effects: in sequence or in parallel

TheSequencecomponent allows you to group together effects that you want to occurone after the other For example, you can use aSequencecomponent to first apply afade effect and then apply a move effect From MXML, you can simply nest theeffects you want to sequence within aSequence tag, as follows:

indi-<mx:TextInput creationCompleteEffect="{sequenceEffect}" />

Trang 23

242 | Chapter 11: Using Effects and Transitions

You can add a pause between sequenced effects using a pause effect You can affectthe length of the pause by specifying a value (in milliseconds) for thedurationprop-erty The following example fades a target, pauses 1,000 milliseconds, and thenmoves the target:

TheParallelcomponent allows you to group together effects that you want to play

at the same time For example, if you want to fade and move a component at thesame time, you can use the following parallel effect:

var sequenceEffect:Sequence = new Sequence( );

sequenceEffect.addChild(rotateEffect);

Note that although effects and display objects both have addChild( )

methods, you cannot add an effect to the display list, nor can you add

a display object to an effect.

Pausing, Resuming, and Reversing Effects

By default, an effect plays straight through However, you can pause, resume, andeven reverse an effect All effects havepause( )andresume( )methods that pause andresume the playback of an effect, respectively

Ngày đăng: 06/08/2014, 08:22

TỪ KHÓA LIÊN QUAN