Tài liệu Flash Builder 4 and Flex 4 Bible- P4 ppt

50 405 1
Tài liệu Flash Builder 4 and Flex 4 Bible- P4 ppt

Đ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

Chapter 4: Understanding the Anatomy of a Flex Application 121 Any code in the external file is compiled as part of the MXML file and the ActionScript class it rep- resents but is executed after objects declared in MXML are instantiated so you can access these objects in your ActionScript code. Because the external file isn’t in XML format, you don’t need to embed the <Script> element or the CDATA block inside the file to protect the code. Follow these steps to create an external ActionScript file: 1. Choose File ➪ New ➪ ActionScript File from the Flash Builder menu. (Don’t select ActionScript Class — that’s a different sort of file I’ll describe in a later chapter.) 2. In the New ActionScript File dialog box, select the folder in which you want to cre- ate the file. External ActionScript files can go anywhere in the project source-code root folder, because you’ll explicitly refer to the file’s location when you link to it from an MXML file. I usually place the file in the same folder as the MXML file it’s linked to. 3. Enter the name of the file. It should have a file extension of .as, but the rest of the file- name is up to you. For an application named HelloWorld.mxml, the matching exter- nal ActionScript file would be helloWorld.as. 4. Click Finish to create the file. Note Notice that in this usage, the external ActionScript filename starts with a lowercase character. This doesn’t have any technical effect on the code, but it’s a way of indicating that it’s a simple file containing ActionScript code, as opposed to an ActionScript class (which, by object-oriented programming conventions, has an initial uppercase character). n After the file has been created, you link to it from the MXML file with the <fx:Script> element and add a source property pointing to the external file. The application in Listing 4.2 embeds its ActionScript code in an <fx:Script> tag set. Caution Any particular <fx:Script> element can contain nested ActionScript or use the source property to link to an external ActionScript file, but it cannot do both at the same time. You can, however, have as many <Script> declarations in a single MXML file as you need. n LISTING 4.2 An MXML application with nested ActionScript <?xml version=”1.0” encoding=”utf-8”?> <s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009” xmlns:s=”library://ns.adobe.com/flex/spark” xmlns:mx=”library://ns.adobe.com/flex/mx” xmlns:components=”components.*”> <fx:Script> <![CDATA[ continued 09_488959-ch04.indd 12109_488959-ch04.indd 121 3/5/10 2:21 PM3/5/10 2:21 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part I: Flex Fundamentals 122 LISTING 4.2 (continued) [Bindable] private var currentResult:Number=0; [Bindable] private var currentInput:String=””; private function calculateHandler(event:Event):void { currentResult += Number(currentInput); currentInput=””; } private function selectHandler(event:TextEvent):void { currentInput += event.text; } ]]> </fx:Script> <s:Panel title=”Calculator” horizontalCenter=”0” top=”20”> <s:layout> <s:VerticalLayout horizontalAlign=”center”/> </s:layout> <mx:Form> <components:ButtonTile id=”input” select=”selectHandler(event)” calculate=”calculateHandler(event)”/> <mx:FormItem label=”Entry:”> <s:TextInput text=”{currentInput}” editable=”false” width=”80”/> </mx:FormItem> <mx:FormItem label=”Total:”> <s:TextInput text=”{currentResult}” editable=”false” width=”80”/> </mx:FormItem> </mx:Form> </s:Panel> </s:Application> On the Web The code in Listing 4.2 is available in the Web site files in the chapter04 project folder as CalculatorWithScript.mxml. n Listing 4.3 shows the same application after the ActionScript has been moved to an external file. LISTING 4.3 MXML application Calculator.mxml with linked ActionScript file <?xml version=”1.0” encoding=”utf-8”?> <s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009” 09_488959-ch04.indd 12209_488959-ch04.indd 122 3/5/10 2:21 PM3/5/10 2:21 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 4: Understanding the Anatomy of a Flex Application 123 xmlns:s=”library://ns.adobe.com/flex/spark” xmlns:mx=”library://ns.adobe.com/flex/mx” xmlns:components=”components.*”> <fx:Script source=”calculator.as”/> <s:Panel title=”Calculator” horizontalCenter=”0” top=”20”> <s:layout> <s:VerticalLayout horizontalAlign=”center”/> </s:layout> <mx:Form> <components:ButtonTile id=”input” select=”selectHandler(event)” calculate=”calculateHandler(event)”/> <mx:FormItem label=”Entry:”> <s:TextInput text=”{currentInput}” editable=”false” width=”80”/> </mx:FormItem> <mx:FormItem label=”Total:”> <s:TextInput text=”{currentResult}” editable=”false” width=”80”/> </mx:FormItem> </mx:Form> </s:Panel> </s:Application> On the Web The code in Listing 4.3 is available in the Web site files in the chapter04 project folder as Calculator. mxml . n You have just as much code to manage, but the XML markup is cleaner and easier to read. And, as shown in Listing 4.4, the ActionScript file now contains only the scripting code: LISTING 4.4 External ActionScript file calculator.as //ActionScript code for Calculator.mxml [Bindable] private var currentResult:Number=0; [Bindable] private var currentInput:String=””; private function calculateHandler(event:Event):void { currentResult += Number(currentInput); currentInput=””; } private function selectHandler(event:TextEvent):void { currentInput += event.text; } 09_488959-ch04.indd 12309_488959-ch04.indd 123 3/5/10 2:21 PM3/5/10 2:21 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part I: Flex Fundamentals 124 On the Web The code in Listing 4.4 is available in the Web site files in the chapter04 project’s src folder as calculator.as. n Managing ActionScript code with Flash Builder Whether you’re working with MXML or ActionScript, Flash Builder’s Outline view enables you to easily find function and variable declarations within the source code. The Outline view appears in the lower-right corner of Flash Builder in the default Flex Development perspective. Using the Outline view with ActionScript When working with MXML, the default Outline view displays a tree of MXML elements. As shown in Figure 4.5, the <fx:Script> element shows up as a single selectable object. New Feature In Flash Builder 4, MXML elements that represent compiler instructions always appear at the bottom of the Outline view, regardless of where they’re placed in the actual code. All visual objects appear at the top of the outline. n FIGURE 4.5 Flash Builder’s Outline view with the MXML editor To navigate to a specific function or variable declaration using the Outline view, click the Show class view icon at the top of the view. As shown in Figure 4.6, you’re now able to click a declara- tion and jump to that bit of code. When using the outline’s Class view, you can change the display with these other options that are accessed from buttons at the top of the Outline view: l Sort. Displays variables and functions in alphabetical order. l Hide Static Functions and Variables. Hides variables and functions that are marked with the static modifier. l Hide Non-Public Members. Hides variables and functions that aren’t marked with the public access modifier. 09_488959-ch04.indd 12409_488959-ch04.indd 124 3/5/10 2:21 PM3/5/10 2:21 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 4: Understanding the Anatomy of a Flex Application 125 FIGURE 4.6 Outline view and the Class view buttons Class view Sort Hide static Hide non-public Note You need to click an item only once in the Outline view to jump to the matching code. n Tip From any object reference in the ActionScript file, hold down Ctrl (Windows) or Ô (Mac) and click the refer- ence to jump to that object’s declaration. This works whether the declaration is in the ActionScript file or an external MXML file and for both custom classes and Flex library classes whose source code has been provided by Adobe. n Flash Builder 4 adds a new documentation feature that enables you to quickly get information about an ActionScript class from the Flex SDK. Move the cursor over a component declaration and wait about one second. As shown in Figure 4.7, a documentation window appears. If the available documentation for that component exceeds the height of the window, you can then press F2 to give the window focus. You can then resize or scroll through the window to see all the available documentation. Managing code in the ActionScript editor When you store ActionScript code in an external file, Flash Builder provides some additional code management tools. Code folding Code folding refers to the capability of the Flash Builder editor to fold, or collapse, certain sections of code and hide them from view. In an MXML editor, code folding is based on the source file’s MXML elements. As shown in Figure 4.8, an MXML file displays code folding icons at the begin- ning of each MXML element. You’ll see a folding icon for the <fx:Script> tag that enables you to collapse that section of code to a single line. 09_488959-ch04.indd 12509_488959-ch04.indd 125 3/5/10 2:21 PM3/5/10 2:21 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part I: Flex Fundamentals 126 FIGURE 4.7 Opening API documentation quickly within Flash Builder FIGURE 4.8 Code folding icons in an MXML file Code folding icons Clicking the icon reduces the MXML element at that line to a single line of displayed code. Then, when you move the cursor over the folding icon, you see a pop-up window showing the first of code in the collapsed section. Clicking the icon again expands it to full display. In an ActionScript file, because you are using Flash Builder’s ActionScript editor, code folding collapses function declarations instead of MXML elements. As shown in Figure 4.9, you can click any function’s folding icon and reduce it to a single line of code. You also can collapse all functions in a file to single-line display: 1. Right-click in the column of line numbers. 2. Choose Folding ➪ Collapse Functions to reduce all functions to single-line displays. 09_488959-ch04.indd 12609_488959-ch04.indd 126 3/5/10 2:21 PM3/5/10 2:21 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 4: Understanding the Anatomy of a Flex Application 127 FIGURE 4.9 Code folding icons in an ActionScript file Code folding icons Now all functions are displayed as single lines of code. And finally, moving the cursor over a folded icon that is in a collapsed state displays the contents of the folded function. Organizing import statements An import statement informs the compiler about the location of ActionScript classes it needs to compile in an application or component. Most ActionScript classes must be explicitly imported to be recognized by the compiler. This import statement makes a class named ArrayCollection available to the compiler: import mx.collections.ArrayCollection; In Flash Builder 2, the development environment helped you build an import list by creating import statements for classes you referred to as you typed. But later, if you removed a class refer- ence from the body of the code, the import statement would be left in the file. This doesn’t cause any harm to the application ( import statements on their own don’t add size or functionality to a compiled application), but it could be confusing later when you opened the file and saw import statements that had nothing to do with the code’s functionality. In Flex Builder 3, the ActionScript editor added the capability to organize an ActionScript file’s import statements with a simple menu selection or keyboard shortcut. When you organize imports, unused import statements are removed and the ones you need are left in alphabetical order, grouped by package. Consider this list of import statements: import mx.controls.Alert; import flash.net.FileFilter; import flash.net.URLRequest; import mx.collections.ArrayCollection; import mx.validators.Validator; import flash.net.FileReference; 09_488959-ch04.indd 12709_488959-ch04.indd 127 3/5/10 2:21 PM3/5/10 2:21 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part I: Flex Fundamentals 128 To organize this list, choose Source ➪ Organize Imports from the Flash Builder menu. (Or press the keyboard shortcut Ctrl+Shift+O.) After organization, the list now looks like this: import flash.net.FileFilter; import flash.net.FileReference; import flash.net.URLRequest; import mx.controls.Alert; import mx.validators.Validator; The import statement for the unused class is removed, and the remaining statements are alpha- betized and grouped by package. In Flash Builder 4, this feature is now available in MXML files as well. Just as with ActionScript files, you can now use the Organize Imports feature to alphabetize and group import statements and remove unused imports in the <fx:Script> sections of your MXML documents. Using the Application Component The Application component is always declared as the root element of an MXML application file. It represents the top level of the application’s containership hierarchy. New Feature The Flex 4 Application component is part of the Spark component set. It replaces the Application con- tainer that was used in previous versions of Flex, now known as the MX Application component. You can still use the MX version if you prefer, but only the new version implements Flex 4’s advanced layout architec- ture and declarative skinning and is compatible with Flex projects created in Flash Catalyst. n The Flex 4 version of the Application component is defined as an ActionScript class with the fully qualified name spark.components.Application. The Application class supports important properties and styles that are not part of other Flex 4 containers. Table 4.2 shows these properties and styles. TABLE 4.2 Application Properties and Styles Property Purpose Example pageTitle A value that’s passed through to the HTML wrapper and displayed in place of the ${title} placeholder. <s:Application pageTitle=”My Flex App”/> backgroundColor A color value stated as a hexadecimal code. <s:Application backgroundColor=”#FF00FF”/> 09_488959-ch04.indd 12809_488959-ch04.indd 128 3/5/10 2:21 PM3/5/10 2:21 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 4: Understanding the Anatomy of a Flex Application 129 Property Purpose Example controlBarContent An array of visual objects that are laid out in a skin part named controlBarGroup and typed as a Group. The default skin “docks” the control bar at the top of the screen. <s:Application > <s:controlBarContent> navigation elements </s:controlBarContent> </s:Application> frameRate The number of frames per second at which changes are reflected in Flash Player. The default in Flex is 24 frames/second. This prop- erty must be set in MXML. <s:Application frameRate=”60”/> url A read-only property returning the URL from which the applica- tion SWF file was opened. var currentURL:String = this. url; Tip You can make typing appear to be smoother in a Flex application by increasing the frameRate. For example, if the cursor is in a TextArea or TextInput control and you hold down a key at 24 frames/second, the effect can be a bit “jumpy.” That is, the characters may not appear at an even rate. Setting the frameRate to 60 or 90 frames/second may noticeably improve this “animation.” In theory, this could have a negative effect on CPU usage on the client system, but in testing on a modern computer, it’s difficult to see a difference. n New Feature The MX version of the Application component had a static property named application that refer- enced the application itself. The commonly used expression was Application.application. In Flex 4, this functionality has been moved to a static property named topLevelApplication, in a new class named FlexGlobals. So, the new version of this expression is FlexGlobals.topLevelApplication. As with the Flex 3 version, this expression is defined in the API to return an Object, but the native type matches the application’s actual name. So, to create a variable that references an application named HelloWorld, use this syntax: private var myApp:HelloWorld = FlexGlobals.topLevelApplication as HelloWorld; n Note The url property refers to the URL from which the application SWF file was loaded. For example, when run- ning the URLDemo.mxml application from the local disk, the browser’s URL is displayed as: file:///C:/flex4bible/chapter04/bin-debug/URLDemo.html The url property returns this value: file:///C:/flex4bible/chapter04/bin-debug/URLDemo.swf n 09_488959-ch04.indd 12909_488959-ch04.indd 129 3/5/10 2:21 PM3/5/10 2:21 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Part I: Flex Fundamentals 130 Passing application parameters You pass parameters to the application from the browser using a special Flash Player variable named flashvars. If you’re using the HTML wrapper file that’s generated during compilation by Flash Builder4, the flashvars variable is declared as a JavaScript object in the HTML wrapper file JavaScript code. You can add your own parameters by declaring named properties of the flashvars object: var flashvars = {}; flashvars.state=”New”; The flashvars object is then passed to Flash Player in the call to swfobject.embedSWF(): swfobject.embedSWF( “${swf}.swf”, “flashContent”, “${width}”, “${height}”, swfVersionStr, xiSwfUrlStr, flashvars, params, attributes); To retrieve these values at runtime, use the Application object’s parameters property. The parameters property is a dynamic object that enables you to address its named properties with dot notation, as in: currentState=this.parameters.state; Note If you’re hosting a Web-based Flex application on a dynamic application server such as ColdFusion or PHP, you can generate the flashvars variable dynamically. n Controlling application dimensions The default values for the Application component’s width and height are both 100 percent. These values are passed to Flash Player through the HTML wrapper file that’s generated by Flash Builder. For example, this code: <s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009” xmlns:s=”library://ns.adobe.com/flex/spark” xmlns:mx=”library://ns.adobe.com/flex/mx” width=”300” height=”200”> </s:Application> results in these values being passed to Flash Player in the generated HTML wrapper page: swfobject.embedSWF( “URLDemo.swf”, “flashContent”, “300”, “200”, swfVersionStr, xiSwfUrlStr, flashvars, params, attributes); 09_488959-ch04.indd 13009_488959-ch04.indd 130 3/5/10 2:21 PM3/5/10 2:21 PM Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... libraries that are compatible with Flex applications can be created with these tools: l Flash CS3 or CS4 l The Flex SDK’s compc command-line component compiler l A Flex Library Project created and managed in Flash Builder In this section, I describe how to create and use a component library in Flash Builder with a Flex Library Project Creating component libraries A Flex Library Project is designed to... in Flash Builder: 1 Choose File ➪ New ➪ Flex Library Project from the Flash Builder menu Tip If you’re using the plug-in version of Flash Builder, choose File ➪ New ➪ Other from the Eclipse menu Then choose Flash BuilderFlex Library Project from the wizard dialog box n 2 In the New Flex Library Project wizard, shown in Figure 5.7, provide a Project name, select the Use default location option, and. .. SkinnableContainer, and uses Flex 4 s new component layout architecture In previous versions of Flex, the application’s layout property was a simple string with possible values of vertical, horizontal, and absolute In Flex 4 components, the layout property is set to an instance of a complex object n The layout property is set to an instance of a class that extends a superclass named LayoutBase These classes and their... Chapter 5: Using Bindings and Components FIGURE 5.5 An application with an instance of a custom component FIGURE 5.6 Dragging a custom component into an application 147 Part I: Flex Fundamentals New Feature In Flex Builder 3, when you dragged a custom component into an application in Design mode and the component package’s namespace prefix hadn’t been previously defined, Flex Builder created an automatically... sample code for this chapter, import the chapter05.fxp Flex project file from the Web site files into your Flash Builder workspace n 135 IN THIS CHAPTER Using binding expressions Creating MXML components Instantiating MXML components Creating component properties and methods Creating and using component libraries Creating Flash- based controls Part I: Flex Fundamentals Using Binding Expressions As I previously... xmlns:s=”library://ns.adobe.com /flex/ spark” xmlns:mx=”library://ns.adobe.com /flex/ mx”> place additional MXML tags here Caution Notice that the MXML component file’s root element includes the same three namespace and prefix declarations as the main application file The http://ns.adobe.com/mxml/2009 namespace is required in all Flex 4 MXML files, and the Spark and MX namespaces are required... available classes appears and the custom component is displayed Tip If the list of available classes disappears, press Ctrl+spacebar to bring it back This works in Flash Builder wherever code hinting is available n 4 Press Enter (Windows) or Return (Mac) to select the custom component from the list of available ActionScript classes Flash Builder completes the code with the namespace prefix and the component...Chapter 4: Understanding the Anatomy of a Flex Application These dimension properties are then passed to the application by Flash Player In contrast the minWidth and minHeight properties that are set automatically on new applications affect only the Flex application itself, and not the HTML wrapper file Setting the layout property The Application... Objects in the display list are laid out in a row from left to right FIGURE 4. 11 An application with horizontal layout 132 Chapter 4: Understanding the Anatomy of a Flex Application Note The HorizontalLayout and VerticalLayout classes require the application to calculate the quantity and size of the nested controls at runtime, and then in a second pass to place them on the screen This calculation has... without explicit event handling or ActionScript statements I describe a couple of binding syntax styles and show when to use each This chapter also includes a description of how to create and use custom MXML components in a Flex application In the last section of this chapter, I describe how to package and manage multiple components and classes in a component library using a Flex Library Project On . implements Flex 4 s advanced layout architec- ture and declarative skinning and is compatible with Flex projects created in Flash Catalyst. n The Flex 4 version. Members. Hides variables and functions that aren’t marked with the public access modifier. 09 _48 8959-ch 04. indd 1 240 9 _48 8959-ch 04. indd 1 24 3/5/10 2:21 PM3/5/10

Ngày đăng: 22/01/2014, 01:20

Từ khóa liên quan

Mục lục

  • Adobe Flash® Builder™ 4 and Flex® 4 Bible

    • About the Author

    • Credits

    • Contents at a Glance

    • Contents

    • Preface

      • Getting the Most Out of This Book

      • Using the Book’s Icons

      • Acknowledgments

      • Part I: Flex Fundamentals

        • Chapter 1: About Flex 4

          • Learning the Fundamentals of Flex

          • Understanding Adobe Flash Player

          • Flex 4 Development Tools

          • Getting Help

          • Summary

          • Chapter 2: Using Flash Builder 4

            • Getting Flash Builder

            • Installing Flash Builder 4

            • Getting to Know Eclipse Features

            • Using Flash Builder

            • Getting Help

            • Searching for Code

            • Generating Code

            • Integrating Flash Builder with Flash Professional CS5

Tài liệu cùng người dùng

Tài liệu liên quan