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

Tài liệu Foundation Flash CS5 For Designers- P14 doc

50 305 0
Tài liệu đã được kiểm tra trùng lặp

Đ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 đề Building Interfaces With The Ui Components
Thể loại tài liệu
Định dạng
Số trang 50
Dung lượng 1,01 MB

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

Nội dung

Using one or more instances of the RadioButton component in your movie will add 16KB to the SWF if no other components share the load.. BUILDING INTERFACES WITH THE UI COMPONENTS Using

Trang 1

BUILDING INTERFACES WITH THE UI COMPONENTS

Here’s an exercise designed to show you how the ProgressBar component works:

1 Open the ProgressBar.fla file in this chapter’s Exercise folder Note that a ProgressBar instance exists in frame 1 with the instance name pb, as well as a text field with the instance name output In frame 5, you’ll find a fairly heavy image of red leaves on a tree branch, snapped

by one of the authors In the scripts layer, there’s a MovieClip.stop() method in frames 1 and 5

2 Click into frame 1 of the scripts layer Note the existing stop() method Type the following

ActionScript after that method (new code in bold):

stop();

root.loaderInfo.addEventListener(Event.COMPLETE,

completeHandler);

function completeHandler(evt:Event):void { play();

};

pb.source = root.loaderInfo;

Here, first, the playhead stops at this frame Next, an Event.COMPLETE handler is assigned to the LoaderInfo instance associated with the root property of the main timeline Say again? Yeah, this one is

a bit different from what you’ve seen

In the same way that the stop() method is invoked here on the main timeline—appearing, as it does, without an object reference prefix—the root property is also being invoked implicitly on the main timeline (root is a property of the DisplayObject class, which means MovieClip and other classes have it by inheritance.) The root property refers to the topmost display object in a given display list In this context, it essentially refers to the display list of the main timeline (everything that’s visible—or will be visible—on the main timeline, including that onion photo on frame 5)

The main timeline, being a movie clip, features a loaderInfo property, which points to an instance of the LoaderInfo class that (as its name suggests) manages loading information for the object at hand In this case, when the movie itself has completed loading, the Event.COMPLETE event is dispatched, and the completeHandler() function invokes MovieClip.play() on the main timeline, causing the playhead to resume play until it encounters the second stop() method on frame 5 It’s frame 5 that reveals the image

Notice that, so far, none of this yet touches the ProgressBar component That happens only at this point

Immediately after the event handler, the ProgressBar.source property, by way of the pb instance, is associated with the root.loaderInfo reference As if by magic, that’s all it takes to set the thermometer-style movement in motion

3 Test the movie When the SWF launches, select View Simulate Download from the SWF’s menu bar to see the ProgressBar component in action Selecting View Download

Settings lets you select the speed of the simulated Internet connection

4 Close the SWF

Trang 2

CHAPTER 11

630

5 Let’s also display a text message indicating a percent loaded In the Actions panel, add a few

more lines below the existing code:

The ProgressBar component features a percentComplete property, which we’re using here The

addEventListener() method is invoked against the pb instance, listening for a ProgressEvent.PROGRESS event The function it performs sets the output text field’s text property to a rounded-down string version of the progress percentage, with the percent sign tacked onto the end for good measure

RadioButton component

Radio buttons are gregarious They belong in groups and courteously defer to each other as each takes the spotlight What are we talking about? We’re talking about a component identical in functionality to radio

buttons in HTML Groups of RadioButton components are used to let the user make a single selection

from a multiple-choice set, as shown in Figure 11-22

Figure 11-22 The RadioButton component lets the user make a single selection from a multiple-choice

set

www.zshareall.com

Trang 3

BUILDING INTERFACES WITH THE UI COMPONENTS

Double-clicking a RadioButton instance provides access to its skins, which you can edit as described in

the “Button component” section Styling works the same way

Using one or more instances of the RadioButton component in your movie will add

16KB to the SWF if no other components share the load

To see RadioButton components in action, open the RadioButton.fla file in this chapter’s Exercise file Because radio buttons work in groups, the Component Parameters tab of the Properties panel has a “collective consciousness” parameter we haven’t seen with other components: groupName Select each of the three radio buttons in turn, and verify that each belongs to the same group, syntax, even though each has its own distinct label: Method, Property, and Operator (see Figure 11-23) Note also

the empty dynamic text field whose instance name is output You’re about to wire up the radio buttons to that text field

Figure 11-23 RadioButton instances must be associated with a group name

Click into frame 1 of the scripts layer, and type the following very condensed but interesting

ActionScript:

rb1.group.addEventListener(Event.CHANGE,

changeHandler);

function changeHandler(evt:Event):void { output.text = rb1.group.selection.label;

};

What makes this interesting? In most of the event-handling samples in this chapter, you’ve invoked the addEventListener() method on an object that you personally gave an instance name Here, that might have been rb1, but that’s not the focal point in this case You’re not adding an event listener to a particular

radio button but rather to the group to which these buttons belong The RadioButton class provides a group property, which means that each instance knows to which group it belongs It’s the group that dispatches the Event.CHANGE event, which occurs when any one of these radio buttons is clicked

It doesn’t matter which radio button’s group property you use, because all of them point to the same RadioButtonGroup instance The associated function updates the output text field by sending it the

Trang 4

are label and value, and the data type of value is typed as Object, not String The

text field wants a string, so you would change that line of ActionScript to output.text

= rb1.group.selection.value.toString(); For example, if you change the value

of the Operator RadioButton to Correct, you turn this exercise into a quiz

ScrollPane component

The ScrollPane component lets you have eyes bigger than your stomach If you want to display a large image—so large that you’ll need scrollbars—ScrollPane is your component; Figure 11-24 shows it

super-in action

Figure 11-24 ScrollPane provides optional scrollbars to accommodate oversized content

ScrollPane has nested skins because of its scrollbars, so double-clicking an instance during authoring will open its skin elements in tiers Styling works the same as described in the “Button component” section, although with no text elements, most of your customization work will probably center around skins

www.zshareall.com

Trang 5

BUILDING INTERFACES WITH THE UI COMPONENTS

Using one or more instances of the ScrollPane component in your movie will add

21KB to the SWF if no other components share the load

In this example, there’s no need for ActionScript

1 Open the ScrollPane.fla file in this chapter’s Exercise folder Select the ScrollPane

instance, and click the Parameters tab of the Component Inspector panel

2 In the Component Parameters area, double-click the right column of the source row Type

Redleaves.jpg

3 Test the movie Pretty slick! The source parameter can be pointed to any file format that Flash

can load dynamically, including JPEGs, GIFs, PNGs, and other SWFs

Slider component

The Slider component is conceptually the same thing as NumericStepper, except that instead of

clicking buttons to advance from one number to the next, the user drags a knob along a slider, as shown in Figure 11-25 You, as designer, are responsible for setting the minimum and maximum values, and this component lets you specify whether sliding is smooth or snaps to increments specified by you

Figure 11-25 Slider lets the user drag a handle back and forth to specify a value

Slider has no text elements, so styling is fairly light What’s there works as it does for the Button component Skinning also works as it does for Button: double-click a Slider instance in the authoring

environment to change the knob and track skins

Using one or more instances of the Slider component in your movie will add 17KB to

the SWF if no other components share the load

To see how the Slider component works, open the Slider.fla file in this chapter’s Exercise folder Note that the instance name for the Slider instance is slider, which works only because ActionScript is

a case-sensitive language You couldn’t call it Slider, because that’s the name of the class that defines this object Also note the instance names circle1 and circle2 on the two circles You’re about to wire

up the Slider component to adjust their width and height

Click into frame 1 of the scripts layer, and type the following ActionScript:

Trang 6

CHAPTER 11

634

slider.addEventListener(Event.CHANGE, changeHandler);

function changeHandler(evt:Event):void { circle1.scaleX = slider.value / 100;

circle2.scaleY = slider.value / 100;

};

When the Event.CHANGE event is dispatched—this happens as the knob moves along the track—the slider’s value property is used to update scaling properties of the circle movie clips Why divide by 100? In movie clip scaling, 0 percent is 0 and 100 percent is 1 Because the Slider instance happens to have its maximum parameter set to 100, the division puts value into the desired range, as shown in

Figure 11-26

Figure 11-26 A single Slider instance can adjust many objects Hey, that looks like a face!

Be sure to experiment with the parameters in the Properties panel’s Component Parameters area Most of them are intuitive, but liveDragging and snapInterval might not be The liveDragging parameter tells Slider whether to update its value property as the knob moves, as opposed to when it is released When you set liveDragging to false (deselected), the circles will resize only after you reposition the knob and then release it The snapInterval parameter tells Slider how often to update its value property To demonstrate, set liveDragging to true (a check mark), and then change

snapInterval to a small number, such as 1 When you drag the knob, you’ll see the circles resize smoothly Change snapInterval to 10 and test again, and the circles resize less smoothly, because

you’re asking value to count by tens

You may be surprised to find a direction parameter (its values are horizontal and vertical) Why not just use the Free Transform tool to rotate this slider? Well, try it We’ll wait that’s kind of weird,

right? It doesn’t work Components are a sophisticated phenomenon, even though they look so simple

Now, what if you want a slanted slider, not horizontal or vertical? Here’s a trick: select the Slider instance, convert it to a movie clip (Modify Convert to Symbol), and give that movie clip an instance name such as sliderClip When both the movie clip and its nested Slider have instance

names, you’re set

sliderClip.slider.addEventListener(Event.CHANGE, changeHandler);

function changeHandler(evt:Event):void { circle1.scaleX = sliderClip.slider.value / 100;

circle2.scaleY = sliderClip.slider.value / 100;

};

www.zshareall.com

Trang 7

BUILDING INTERFACES WITH THE UI COMPONENTS

TextArea component

Chapter 6 introduced you to text fields and containers Consider the TextArea component a text field in a

tux It has an attractive, slightly beveled border, lets you limit how many characters can be typed into it (like input text fields), and is optionally scrollable (see Figure 11-27) This component is akin to the

<textarea> element in HTML

Figure 11-27 TextArea is the James Bond of text fields

TextArea is skinnable, but the parts are few You’ll see a nested skin for the scrollbars when you click an instance in the authoring environment More likely, you’ll want to style its text contents, which works as described in the “Button component” section

double-Using one or more instances of the TextArea component in your movie will add 21KB

to the SWF if no other components (other than the automatically included

UIScrollBar ) share the load

Open the TextArea.fla file in this chapter’s Exercise folder to see an example of populating a

TextArea instance with text (We figured it would be cruel to make you type in a lengthy bit of sample text

on your own.) Note that the TextArea component can display HTML text, as shown in the sample file, or

plain text Use the component’s ActionScript htmlText or text properties accordingly

Notice that the Component Parameters tab of the Properties panel shows only a text parameter for

supplying text We can’t imagine anyone using that tiny space to enter more than a sentence, so reference that parameter as a property in your ActionScript Assuming ta is the TextArea component’s instance name, here’s the code:

Trang 8

CHAPTER 11

636

ta.htmlText = "<p>HTML text here, with styling.";

or it could look like this:

ta.text = "Plain text content here.";

TextInput component

The TextInput component is the single-line kid brother of TextArea For this reason, to trump it up,

we’ll show it displaying one of the shortest short stories in the world, attributed to Ernest Hemingway (see Figure 11-28)

Figure 11-28 TextInput is a single-line component, mainly used for user input

TextInput is primarily used to collect typed user input, like HTML-based “Contact Us” forms, and can

even be set to display password characters as asterisks (see the displayAsPassword parameter) The

component is skinnable—just double-click an instance in the authoring environment—but there’s not much

to skin Styling works as described in the “Button component” section

Using one or more instances of the TextInput component in your movie will add 15KB

to the SWF if no other components share the load

To see the TextInput component in action, open the TextInput.fla file that accompanies this chapter Note the two TextInput instances, with instance names input (top) and output (bottom) Select each component in turn, and look at the Parameters tab of the Component Inspector panel as you do For the top TextInput instance, the displayAsPassword and editable parameters are set to true For the bottom one, both of those parameters are set to false You’re about to make the upper component

reveal its password to the lower one

Click into frame 1 of the scripts layer, and type the following ActionScript:

input.addEventListener(Event.CHANGE, changeHandler);

function changeHandler(evt:Event):void { output.text = input.text;

};

As text is typed into the upper TextInput instance, the Event.CHANGE handler updates the lower

instance’s text content with that of the upper instance’s content Because of the parameter settings, the text content is hidden above but clearly displayed below

www.zshareall.com

Trang 9

BUILDING INTERFACES WITH THE UI COMPONENTS

TileList component

TileList is not unlike the ScrollPane component Both load files for display, optionally with scrollbars, but TileList displays numerous files—JPEGs, SWFs, and so on—in the tiled arrangement shown in

Figure 11-29

Double-click a TileList instance to edit its skins You’ll see a second tier of skins for the scrollbars

Styling may be accomplished as described in the “Button component” section

Using one or more instances of the TileList component in your movie will add 32KB

to the SWF if no other components share the load

Figure 11-29 TileList displays a tiled arrangement of content, optionally scrolling as necessary

Quite a few parameters are listed in the Component Parameters area of the Properties panel for this

component, but they’re all easy to grasp For example, there are settings for the width and number of

columns, height and number of rows, direction or orientation (horizontal or vertical), and scrolling settings (on, off, and auto, the last of which makes scrollbars show only as necessary) The

dataProvider parameter is the most important, because that’s where you define the content to show It

works the same as the dataProvider for ComboBox, except that instead of label and data properties,

TileList expects label and source

If you find the Component Parameters a bit confining, you can always use ActionScript to add items to the TileList To try this, open the TileList.fla file in the Chapter 11 Exercise folder Note that the

Trang 10

};

The first three lines use practically the same approach we used for adding an additional item to the

ComboBox instance in that section of the chapter Mugs 1 through 5 are specified in the Properties

panel Here, these three lines of code give us a few more mug shots (heh, mug shots—we love that joke)

In the event handler, the changeHandler() function updates the output text fields’ text property with the

label value of the TileList’s selected item

TileList also supports multiple selections, like the List component The sample

code in the “List component” section provides the same basic mechanism you would use here, except instead of targeting the data property, you’ll probably want to target label,

as shown in the preceding single-selection sample

UILoader component

If the Flash CS5 UI components all went to a Halloween party, UILoader would show up as the Invisible

Man (see Figure 11-30)

Figure 11-30 Practically speaking, UILoader has no visual elements (and yes, this figure is empty; being

able to include it cracks us up)

www.zshareall.com

Trang 11

BUILDING INTERFACES WITH THE UI COMPONENTS

So, what’s the point? Ah, but UILoader is such a selfless, giving component! Its purpose is to load and

display content other than itself This lets you avoid using the Loader class (which you’ll encounter in Chapter 14), just in case the thought of ActionScript makes you feel like you discovered half a worm in

your apple Simply enter a filename into the source parameter of the Properties panel’s Component

Parameters area, and you’re set (see Figure 11-31)

Figure 11-31 Just enter in the name of a supported file format, and Flash will load it

Using one or more instances of the UILoader component in your movie will add 15KB

to the SWF if no other components share the load

Here’s a UILoader component exercise:

1 Open the UILoader.fla file that accompanies this chapter Double-click the UILoader

instance, and you’ll see message that no skins are available Since we aren’t speaking to this component with ActionScript (yet), it doesn’t need an instance name

2 In the Parameters tab of the Component Inspector panel, enter the filename

Redleaves.jpg into the right column of the source row This references a JPG file in the same

folder as your FLA

3 Test your movie, and you’ll see the leaves load into its UILoader container

4 Deselect the maintainAspectRatio parameter and test again This time, the image loads a bit squished Our personal preference is usually to maintain aspect ratio The scaleContent

parameter determines whether the loaded content is scaled or cropped in its container

Trang 12

CHAPTER 11

640

5 Our friend ProgressBar is about to make a cameo appearance Drag an instance of the

ProgessBar component to the stage below the UILoader instance, and give the UILoader

instance the instance name loader

6 Select the ProgressBar instance, and in the Parameters tab, set its source parameter to loader—that’s the instance name you just gave the UILoader instance (see Figure 11-32) You’re associating the two and telling the ProgressBar component to check with the UILoader

component to divulge how much of the requested file has loaded

Figure 11-32 It’s very easy to show the load progress for a UILoader instance

7 Test your movie again

8 In the SWF’s menu bar, select View Simulate Download to see some super-easy

preloading action

9 Close the SWF

10 To wrap up, let’s add a teensy bit of ActionScript (Don’t worry, that half a worm we mentioned earlier was just a centipede—half a centipede.) To make sure ActionScript talks to the

ProgressBar instance, give it an instance name We’re using pb Click into frame 1 of the

scripts layer, and type the following ActionScript:

pb.addEventListener(Event.COMPLETE, completeHandler);

function completeHandler(evt:Event):void { removeChild(pb);

Trang 13

BUILDING INTERFACES WITH THE UI COMPONENTS

UIScrollBar component

If you read any other sections of this chapter, you’ve probably already been introduced to the

UIScrollBar component This component is a humble but useful member of the team, because it allows

other components to have scrollbars UIScrollBar is skinnable by double-clicking any instance in the

authoring environment Styling doesn’t make much sense, but it is possible as described in the “Button component” section

Using one or more instances of the UIScrollBar component in your movie will add

18KB to the SWF if no other components share the load

So as to avoid repeating ourselves, we’ll direct your attention to the “Using the UIScrollBar component” section in Chapter 6 to see this component in action

What you have learned

In this chapter, you learned the following:

 How to use every one of the Flash CS5 UI components

 How to write the ActionScript that controls components

 How to skin a component

 How to manage components in a Flash movie Clients are fickle One day the black Times Roman they asked for is fabulous, and the next day it “just has

to be” green Helvetica Narrow This can be a huge waste of time They start with one image and suddenly there are 100 You can spend hours opening Flash files and physically making the changes, or pawing through ActionScript looking for code that formats text or handles the images Is there an easier way? XML We have been talking about it throughout this book, and the time has arrived for you to explore XML’s powerful relationship with Flash

Intrigued? Turn the page

Trang 14

www.zshareall.com

Trang 15

Chapter 12 XML (Dynamic Data)

To this point in the book, we have dangled the use of XML in front of you with no real explanation of how it works That time has arrived

Flash is a social creature Not only does it rub elbows with HTML—coexisting happily with text, JavaScript, images, audio, video, CSS, and more—but it can also reach out past its own SWF boundaries to collaborate with data hosted on a server

In the hands of an experienced programmer, Flash can interact with database applications by way of the URLLoader and URLVariables classes, perform web service and Flash remoting calls, and even slap a secret handshake with Ajax, thanks to the ExternalInterface class All this from a browser plug-in that began its life as a way to improve on animated GIFs! It’s easy to see why Flash has become a widespread phenomenon, and its versatility makes equally social creatures of the countless designers and developers who end up warming their diverse mitts around the same campfire because of it

This book isn’t here to make programmers out of artists We don’t have the page count to delve into most

of the concepts just mentioned, but we are going to introduce you to a markup language called XML that, with a bit of help from ActionScript, can make your SWFs dynamic

Here’s what we’ll cover in this chapter:

 Retrieving and filtering XML data using E4X syntax

 Using retrieved data in collaboration with ActionScript The following files are used in this chapter (located in Chapter13/ExerciseFiles_Ch13/Exercise/):

Trang 16

If you haven’t already worked with XML, we bet our next single malt Scotch you’ve at least heard of it The letters stand for eXtensible Markup Language, and extensibility—the ability to create your own HTML-like tags—is almost certainly the reason XML has become a towering champ in data communication Countless markup languages and file formats are based on XML, including SMIL, RSS, XAML, MXML, RDF, WAP, SVG, SOAP, WSDL, OpenDocument, XHTML, and so on—truly more than would fit on this page We’ll leave the letter combinations to a Scrabble master

“That’s fine and dandy,” you might be saying, “but, guys, what is XML?” Fair enough The remarkable thing

about this language is that it can basically be whatever you want it to be, provided you stick by its rules The W3C defines the syntax recommendation for XML (XML 1.0, fifth edition, which is the latest at the time this book was written) at www.w3.org/TR/2008/REC-xml-20081126/

The main purpose of XML is to let you share data In fact, XML is so flexible that newcomers are often baffled about where to even begin On paper—or rather, on the screen—XML looks a lot like another famous W3C specification: HTML However, rather than using the predetermined tags and attributes supplied by HTML, XML lets you organize your content into descriptive tags of your own design While HTML formats data for display, XML actually describes data The combination of familiar, hierarchical format and completely custom tags generally makes XML content easy to read, both to computers and to humans By separating your data from the movie, you give yourself the opportunity to change content from the outside, affecting SWFs without needing to republish them

In a minute you are actually going to write the following XML:

If you are new to this language, we’ll bet you looked at it and thought, “Has something to do with a bunch

of Flash books.” You are correct, and that’s the beauty and simplicity of XML There is nothing here about formatting text or any other stuff All it does is present data—a list of Flash books

So, are you ready to write some XML?

www.zshareall.com

Trang 17

XML (DYNAMIC DATA)

Writing XML

Here’s a typical scenario One of the authors has a rather extensive collection of Flash books in his office The collection expands and contracts based upon the current version of Flash, and he thinks it would be rather neat to keep a running inventory of his collection Rather than list all 50 or 60 of them, he decides to start out with 5 core titles and grow from there The reason for the 5 titles is simple: if he can get 5 books organized, then it is no big deal to get 50, 500, or even 5,000 books into the document

The decision is to start with books from friends of ED, and he decides to start with: ActionScript 3.0 Image

Effects, Flash Applications for Mobile Devices, ActionScript for Animation, Foundation ActionScript 3.0,

and Flash Math Creativity Each book has its own page count, author, and publisher Where to begin?

Let’s take a look

Every XML document must have at least one tag, which constitutes its root element The root element

should describe the document’s contents In this case, we’re dealing with Flash books, so let’s make that our root:

Note that each opening tag has a closing tag partner (with a slash in it), which is a characteristic required

by the XML standard If an element doesn’t contain further data inside it, that element can optionally serve

as its own opening and closing tags In such a case, the <book></book> pairing would look like this:

<book /> But here, each book has a title, so these elements will remain as tag pairs

Trang 18

The difference here is that the <title> tags contain textual data instead of additional elements, but you

get the idea Hold on a minute—all of these tags contain data! The <title> tags contain text nodes (that

is, nonelement text content), and the <book> and <flashbooks> tags contain XML element nodes (that is, descriptive tags) It doesn’t take much effort to connect the rest of the dots An excerpt of the completed document might look something like this:

Actually, that isn’t complete after all, is it? The author is missing The thing about these books is there may

be one author on the cover or a number of authors on the cover For that, another tier of elements is in order:

Trang 19

The exact same information is conveyed The only difference now is that some of the data has been

shifted to tag attributes, or attribute nodes, rather than tags HTML provides the same mechanism, by the

way Consider the src attribute of an <img> tag (<img src="someImage.jpg" />) All it does here is change how the data would be retrieved, as you’ll see in the “Using E4X syntax” section of this chapter Which approach is better? Honestly, the choice is yours It’s not so much a question of “better” as it is what best matches your sense of orderliness Ironically, this open-ended quality, which is one of XML’s strongest assets, is the one feature that is the hardest for those who are new to the subject to grasp It doesn’t have to make sense to anyone but you

Working with and structuring an XML document follows the first principle of web development: “No one cares how you did it They just care that it works.” Find what works best for you, because in the final analysis, your client will never pick up the phone and say, “Dude, that was one sweetly structured XML document you put together.”

Having said that, if you are part of a collaborative work group, be sure that everyone involved agrees on terminology before you start

Folks, this is a bit like a ceramics class As long as you’re careful around the kiln, no one can tell you whose vase is art and whose isn’t Just work the clay between your fingers, let a number of shapes mull

Trang 20

CHAPTER 12

648

around your mind, and then form the clay into a structure that appeals to you While you’re at it, keep a few rules in mind:

 If you open a tag, close it (<tag></tag>)

 If a tag doesn’t come in two parts—that is, if it contains only attributes, or nothing at all—make sure it closes itself (<tag />)

 Close nested tags in reciprocating order (<a><b><c /></b></a> is correct, but

<a><b><c /></a></b> will “blow up”)

 Wrap attribute values in quotation marks or single quotation marks (<tag done="right" />,

<tag done=wrong />)

The flashbooks example we just discussed would be saved as a simple text file with the xml file extension, as in flashBooks.xml In fact, it isn’t a bad idea, once you have finished writing your XML document, to open it in a browser like Firefox to see whether there are any problems

Now that our introductions have been made, let’s get social

Feel free to use a text editor such as Notepad on Windows or TextEdit on the Mac to create your XML files Just be sure you add the xml extension to the file’s name If you

have Dreamweaver CS5, that’s even better, because it automatically writes the document declaration for you at the top, and it offers tools such as code completion to speed up your workflow Also, keep in mind that manually writing XML is just one approach As you start becoming more comfortable with using XML, you will eventually find yourself drifting toward server-side scripting—such as PHP—to handle complex data management

Loading an XML file

XML in Flash has had a rather rocky relationship simply because, until a couple of years ago, it was right

up there with beating yourself in the head with a brick Things have changed, significantly for the better The ActionScript required for loading an XML document isn’t complicated You’ll need an instance of the XML and URLLoader classes, and, of course, an XML document In our case, the document will always be

an actual XML file, although XML documents can be built from scratch with ActionScript

Open the LoadXML.fla file that accompanies this chapter Click into frame 1 of the scripts layer, and

open the Actions panel to see the following code:

var xmlDoc:XML = new XML();

var loader:URLLoader = new URLLoader();

var req:URLRequest = new URLRequest("flashBooks.xml");

loader.load(req);

www.zshareall.com

Trang 21

XML (DYNAMIC DATA)

loader.addEventListener(Event.COMPLETE, completeHandler);

function completeHandler(evt:Event):void { loader.removeEventListener( Event.COMPLETE, completeHandler );

Line 4 then invokes the URLLoader.load() method on the loader instance, specifying req as the parameter The req parameter’s value—"flashBooks.xml" in this example—is the name of your XML file, including a file path if necessary This procedure starts the load process, but the data isn’t available until the XML document has fully arrived from the server For this reason, the final block attaches an Event.COMPLETE listener to the loader instance and then defines the associated function, completeHandler()

In response to a completely loaded document, the event handler function sets the value of the xmlDoc instance to the data property of the target property of the evt parameter passed into the function That’s

a mouthful, but you’ll understand it when we look at the expression in smaller chunks

To begin with, we remove the event listener attached to the XML loader to keep our code clean The incoming parameter, evt, is an instance of the Event class As is possible with any other class, Event features properties, one of which is called target The target property refers to the object that dispatched this event in the first place, which is xmlDoc Being an instance of the XML class, xmlDoc features a data property, which refers to the text content of the flashBooks.xml file—in other words, the actual XML data To let Flash know it should interpret this text content as XML, the expression evt.target.data is wrapped inside a pair of parentheses (()) and preceded by XML This is called

casting, where one data type (String) is converted to another compatible type (XML), and the expression

is passed to the xmlDoc variable At this point, the text file’s XML tags become a “living XML object” inside the SWF, accessible via the xmlDoc variable

To prove it with this sample, a trace( xmlDoc) function call sends the full set of book nodes to the

Output panel Test the movie, and compare the Output panel’s content to the flashBooks.xml file

itself, which you can open with Dreamweaver CS5 or any simple text editor

The preceding sample code will serve as the basis for all loading for the rest of the chapter It’s really that

simple Even better, ActionScript 3.0 makes it just as easy to actually use XML, so let’s jump right in

Using E4X syntax

In ActionScript 2.0, interacting with an XML class instance was, as we said, like beating yourself on the head with a brick This was because of the way XML nodes were accessed once loaded, which wasn’t by the practical tag names supplied earlier in the chapter

Trang 22

CHAPTER 12

650

Until Flash CS3 (and therefore ActionScript 3.0) arrived on the scene, XML in Flash was not up there on the list of “cool things I really need to do.” In fact, many designers and developers (one of the authors among them) regarded the use of XML as being akin to slipping on ice and, on the way down, knowing you were in for a world of hurt

Readers familiar with Flash XML prior to CS3 will doubtless groan to remember obtuse expressions, such

as xmlInstance.firstChild.firstChild.childNodes[2] Flash developers used properties like firstChild and childNodes because they had to, not because it was fun Then there was the now defunct XMLConnector component, which complicated things more than it simplified the process ActionScript 3.0 does away with this groping, thanks to something called E4X

Dots and @s

What is E4X, and what makes it so good? Seemingly named after a military missile project, those three characters form a cutesy abbreviation of ECMAScript for XML It’s an ECMA International specification that has been around for a while, but it provides a completely new, simplified way to access data in an ActionScript 3.0 XML instance

What’s ECMA? The letters stand for European Computer Manufacturers Association, which was formed in 1961 They got together a few years back to devise the ECMAScript Language Specification, which is the basis for JavaScript and ActionScript

They have moved quite beyond their computer roots, and today the organization is officially known as Ecma International

In E4X, element nodes are referenced by the name you give them Paths to nested elements and attributes are easily expressed by a neatly compact syntax of dots (.) and at symbols (@) This syntax closely matches the dot-notation pathing you’re familiar with from the Twinkie example in Chapter 4 Let’s see how it works If you haven’t done so already, open the LoadXML.fla file in this chapter’s

Exercise folder Click into frame 1 of the scripts layer, and open the Actions panel to reveal the

ActionScript The trace() function at line 9 is about to illustrate a number of dynamite E4X features

Testing the movie as it stands puts the full XML document’s contents into the Output panel, as shown

Trang 23

So far, so good But if you don’t care about the root element, <flashbooks>, and simply want to see the

<book> elements, update the trace() line to read trace(xmlDoc.book); Once you do that, test the movie again This time, the <flashbooks> tag doesn’t show, because you’re accessing only its children

Trang 24

trace(xmlDoc.book[0].@title);

To see the second <book> element’s title, substitute 0 with 1; to see the third, substitute 1 with 2; and so

on Based on this pattern, the last element’s title attribute would be xmlDoc.book[4].@title But we know to use the number 4 only because we’re aware how many <book> elements there are What if we didn’t know? In that case, it helps to understand exactly what you’re getting back from these E4X results What you’re getting are instances of the XMLList class, and that means you can invoke any of the methods that class provides on these expressions

For example, you’ve already seen that the expression xmlDoc.book returns a list of all the <book> elements That list is a bona fide XMLList instance So, by appending an XMLList method—say, length()—to the expression, you get something useful (in this case, the length of the list, which is 5) We know that in this context counting starts with zero, so to see the title attribute of the last <book> element, put the following somewhat complex expression inside the array access operator ([]):

In the Output panel, you’ll see that the combined results run together, as shown in Figure 12-1 This is

because these attributes don’t have any innate formatting They aren’t elements in a nested hierarchy; they are just individual strings

www.zshareall.com

Trang 25

XML (DYNAMIC DATA)

Figure 12-1 Unless they have their own line breaks, attributes will run together

In this situation, another XMLList method can help you To make each title appear on its own line, append toXMLString() to the existing expression:

trace(xmlDoc.book.@title.toXMLString());

Swap title for the pageCount attribute, as follows:

trace(xmlDoc.book.@pageCount.toXMLString());

As shown in Figure 12-2, you’ll see page counts for each book instead of titles in the Output panel

Figure 12-2 Any element’s attributes can be retrieved

What about looking at a list of the authors? Viewing individual authors is just as easy Update the trace() function to look like this:

trace(xmlDoc.book[0].authors author [1]);

This trace() function instructs Flash to look at the first <book> element’s <authors> element and then pull out that node’s second <author> element, which happens to be Weyert De Boer For fun and to see how easy E4X makes things for you, contrast the preceding intuitive reference with its ActionScript 2.0 equivalent: xmlDoc.firstChild.firstChild.firstChild.childNodes[1] Which would you rather use?

Moving back to the kinder, gentler world of ActionScript 3.0, update the trace() function as follows to see the whole 15-member cast of the fourth book:

trace(xmlDoc.book[3].authors author);

Ngày đăng: 15/12/2013, 01:16

TỪ KHÓA LIÊN QUAN