Adobe Flex 4 Training from the Source Volume 1 phần 10 docx

50 287 0
Adobe Flex 4 Training from the Source Volume 1 phần 10 docx

Đ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

ptg 432 LESSON : Creating Custom ActionScript Components Reexamining the image from earlier, you will see your current shopping cart item view on the le and the proposed shopping cart item view on the right. ey look quite a bit dierent, but there are functional dierences as well. When you are deciding on a base class, you are trying to determine if there is another class that already does most of the needed work on your behalf. For instance, earlier you created ProductList. You did so by extending the DataGroup and changing a few things to make ProductList a viable component for your needs. In this case, you are making a component that has an area to display a list of items. It also has an area to display the number of items in the cart, an area to display a total, and a View Cart button. Unlike ProductList, this component doesn’t exactly mirror the functionality of any one Flex component. Instead, it is a composite of many dierent components interacting in a specic way. As there isn’t a component in Flex that provides you with the needed functionality, it will be up to you to build it all. While doing so, you are also going to allow for others in the future to change the way your component looks via skinning. erefore, you will use SkinnableComponent as your base class. Creating the Class Yo u w i l l b e g i n b u i l d i n g t h e c o m p o n e n t t o r e p l a c e t h e s h o p p i n g c a r t i t e m s l i s t c u r r e n t l y i n ShoppingView. Start by creating a new ActionScript class. 1 Open the FlexGrocer project that you used in the previous lessons. Alternatively, if you didn’t complete the previous lesson or your code is not function- ing properly, you can import the FlexGrocer.fxp project from the Lesson18/start folder. Please refer to Appendix A for complete instructions on importing a project should you ever skip a lesson or if you ever have a code issue you cannot resolve. From the Library of Wow! eBook Download from www.eBookTM.com ptg 433 Defining a Component 2 Right-click the components package in the Package Explorer. Choose New > ActionScript Class. 3 Specify ShoppingList as the Name of the new class and SkinnableComponent as the superclass. 4 Click Finish. Now that you have a class, you need to dene the interface explained earlier in code. e steps in this section rely heavily on Flash Builder. Learn to use these tools well, and you will save immense amounts of time. 5 Above the constructor for the ShoppingList class, create a new private variable named shoppingCart of type ShoppingCart. private var shoppingCart:ShoppingCart; Be sure to use code completion when typing so that Flash Builder imports cart.ShoppingCart on your behalf. 6 Right-click shoppingCart in the line of code you just wrote. From the pop-up menu, choose Source > Generate Getter/Setter. From the Library of Wow! eBook Download from www.eBookTM.com ptg 434 LESSON : Creating Custom ActionScript Components 7 e Generate Getter/Setter dialog box opens. Ensure your options look the same as those in the following image: is dialog box will generate a new getter and setter function on your behalf, saving you typing and typos. 8 Click OK. You should now have a getter and setter function for a shoppingCart property, and your original variable will be renamed with an underscore. private var _shoppingCart:ShoppingCart; public function get shoppingCart():ShoppingCart { return _shoppingCart; } public function set shoppingCart(value:ShoppingCart):void { _shoppingCart = value; } is property was the rst of three things that made up the ShoppingList interface. e remaining two are both events, which you will add next. 9 Move to just above the ShoppingList class denition and add event metadata for an event named addProduct that will dispatch an event of type events.ProductEvent. [Event(name=”addProduct”,type=”events.ProductEvent”)] 10 Add another piece of event metadata just below the last for an event named viewCart, which will dispatch an event of type flash.events.Event. [Event(name=”viewCart”,type=”flash.events.Event”)] From the Library of Wow! eBook Download from www.eBookTM.com ptg 435 Defining a Component 11 Manually import the two event classes at the top of your le. import events.ProductEvent; import flash.events.Event; 12 Save this le. Yo u r p u b l i c i n t e r f a c e i s n o w c o m p l e t e , a n d y o u c a n c h a n g e y o u r M X M L t o u s e y o u r n e w component. Using Your Custom Class Although your new component does not yet have any functionality useful to the user, its public interface is complete. is means you can replace your existing code with this new component. is is a great way to check your design and ensure you met all the requirements before continuing with implementation. If your component can be dropped into the place where it is eventually needed, you likely have the basics covered. 1 Open the ShoppingView from the views package. 2 Find the VGroup named cartGroup that contains the components responsible for show- ing the cart’s contents in dierent views. 3 Delete the List control, the Label that displays the cart total, and the Button that is responsible for switching to the cartView state. Your code for this VGroup should look like this: <s:VGroup id=”cartGroup” width.cartView=”100%” height=”100%”> <components:CartGrid id=”dgCart” includeIn=”cartView” width=”100%” height=”100%” dataProvider=”{shoppingCart.items}” removeProduct=”removeProductHandler( event )”/> <s:Button includeIn=”cartView” styleName=”cartButton” label="Continue Shopping" click="this.currentState=''"/> </s:VGroup> 4 Next, add your ShoppingList component just above the dgCart but still inside cartGroup and pass it a reference to the shoppingCart. Previously, the List was only included in State1, so also add that logic to this tag. <components:ShoppingList includeIn=”State1” shoppingCart="{shoppingCart}"/> From the Library of Wow! eBook Download from www.eBookTM.com ptg 436 LESSON : Creating Custom ActionScript Components 5 Now handle the addProduct event by calling the addProductHandler event listener, which is already dened in this view. <components:ShoppingList includeIn=”State1” shoppingCart=”{shoppingCart}” addProduct="addProductHandler(event)" /> Tec hn ica lly thi s comp one nt a lr ea dy ha s a re fe re nc e to th e shoppingCart, which means you could manually add a new product anytime you wanted without dispatching and handling this event. However, there are two good reasons not to do so. First, there is already logic on this view to handle the Add Product button click from the ProductList. Reusing this logic means less duplication, but more importantly it means if this logic needs to change, it changes in only one place. Further, while you are making this component more specic, it is still best to separate the logic that your application performs from the way it is displayed. is component is about displaying items in a specic way and interacting with the user. You really don’t want it to also have the responsibility of understanding how products are added to the cart or you’re back to having components that know too much—part of what we’re cor- recting by moving some of this code out of ShoppingView. 6 Handle the viewCart event by setting currentState to cartView. e nal tag should look like this: <components:ShoppingList includeIn=”State1” shoppingCart=”{shoppingCart}” addProduct=”addProductHandler(event)” viewCart=”currentState=’cartView’”/> Yo u r n e w c o m p o n e n t i s n o w t a k i n g t h e p l a c e o f t h e o l d e r p i e c e s , b u t t h e r e i s n o w e x t r a - neous code in ShoppingView that can be eliminated—the functionality will be moved into the ShoppingList component. 7 Delete the renderProductName(), cartList_dragEnterHandler(), and cartList_dragDropHandler() methods from ShoppingView. You may also delete the following imports, which were only used by these methods. import mx.core.IUIComponent; import mx.events.DragEvent; import mx.managers.DragManager; e functionality of these methods belongs to the ShoppingList now and will no longer be needed in ShoppingView. From the Library of Wow! eBook Download from www.eBookTM.com ptg 437 Creating the Visuals 8 Save all your les. You shouldn’t see any compilation errors, but if you were to run this code now you’d receive an error at run time. Yo u p r e s e n t l y h a v e f u n c t i o n w i t h n o f o r m . Yo u ’ v e l e a r n e d t h a t c o m p o n e n t s b a s e d o n SkinnableControl are really two halves, one side representing the function and the other the form. Flex can’t gure out what you want displayed on the screen. You will deal with that issue next. Creating the Visuals Yo u c r e a t e d t h e s t u b f o r y o u r n e w c u s t o m c o m p o n e n t i n t h e p r e v i o u s s e c t i o n , b u t n o w y o u w a n t to dene its visual appearance and then link the two together. Dening the requirements for these two components to talk and establishing the visual display will be the focus of this section. Specifying the Skin Requirements Components that support skinning in Flex are composed of two pieces. is separation provides enormous capability but also some complexity. e two halves need to communicate and they need to set requirements for each other. e functional side of the component in your case will be responsible for displaying the total. erefore, it needs to know that there will be a label created by the visual side allowing that to happen. ese requirements are set via three metadata tags that collectively help tame the madness of this dynamic component model. You learned about these tags briey in Lesson 17, “Customizing a Flex Application with Skins”; however, you will now use them to dene your component. e rst metadata tag is called SkinPart. e SkinPart metadata is responsible for dening what pieces are required of the skin to be considered legitimate. Using your component as an example, the ShoppingList will need to indicate that it needs some place to put the total, the From the Library of Wow! eBook Download from www.eBookTM.com ptg 438 LESSON : Creating Custom ActionScript Components quantity, and the items. e Flash Builder environment will not allow someone to assign a skin to your component that does not implement all these required parts. e SkinPart metadata is used inside the class and above a property. In this example: [SkinPart(required=”true”)] public var myLabel:Label; a component is indicating that the skin must have a Label named myLabel to be considered a valid skin. If required is set to false, it is optional for the skin to implement. e next piece of metadata is called SkinState. e SkinState metadata tag is responsible for indicating what states are required of the skin. e simplest example of this is the normal and disabled state. In Flex you can set the enabled property for any UIComponent to false. Doing so should prevent interaction with the component and oen changes the component visually to ensure the user perceives the reason for the lack of interaction. [SkinState(“normal”)] [SkinState(“disabled”)] When this metadata is added above the class declaration for a component, it means that any skin for this component must have these two states dened. It does not prescribe what the skin does during a state change. For instance, it is completely your choice if the skin blinks or does nothing in a disabled state, but it must be able to handle this state change in whatever way you see t. e nal piece of metadata important to skinning resides in the skin itself. is piece of meta- data is called HostComponent. [HostComponent(“components.MyList”)] e HostComponent tag is used to associate a skin with its component. In other words, it is used to indicate which halves make the whole. is is extremely important as it allows Flash Builder to do compile-time checking on your behalf. If you create a new skin and specify it is for a particular component, Flash Builder can check the SkinState and SkinPart metadata of the named component and verify that your skin meets those requirements. at way, you know at compile time, instead of run time, if there is a problem. 1 Open the ShoppingList.as le that you used in the previous exercise. Alternatively, if you didn’t complete the previous lesson or your code is not functioning properly, you can import the FlexGrocer-PreSkin.fxp project from the Lesson18/intermediate folder. Please refer to Appendix A for complete instructions on importing a project should you ever skip a lesson or if you ever have a code issue you cannot resolve. From the Library of Wow! eBook Download from www.eBookTM.com ptg 439 Creating the Visuals 2 Directly below the event metadata and before the class denition, add two SkinState metadata tags dening states named normal and disabled. [SkinState(“normal”)] [SkinState(“disabled”)] Yo u a r e s p e c i f y i n g t h a t a n y o n e m a k i n g a s k i n f o r y o u r c o m p o n e n t m u s t b e a b l e t o h a n d l e these two states or it is not to be considered a valid skin. 3 Inside the class denition, just below the variable declaration for the _shoppingCart property, add a public variable named totalLabel of type Label. Be sure to use code completion, but also be sure that you specify spark.components.Label. cauTioN! While working in ActionScript in Flex 4, you must be extremely careful about class names. Because MX and Spark components both have a Label, Button, and other similar classes, it is extremely easy to import the wrong one. Remember when skinning, that you almost always want the Spark versions. The following error is typical of choosing the wrong Label when creating a skin. 4 Directly above the totalLabel property, add the SkinPart metadata, indicating that this particular part is required. Your code should look like this: [SkinPart(required=”true”)] public var totalLabel:Label; 5 Add a new required SkinPart for dataGroup of type DataGroup. [SkinPart(required=”true”)] public var dataGroup:DataGroup; 6 Add another new required SkinPart for quantityLabel of type Label. [SkinPart(required=”true”)] public var quantityLabel:Label; From the Library of Wow! eBook Download from www.eBookTM.com ptg 440 LESSON : Creating Custom ActionScript Components 7 Finally, add an optional SkinPart for viewCartBtn of type Button. [SkinPart(required=”false”)] public var viewCartBtn:Button; In all cases, be sure that you used code completion and that you choose the Spark ver- sions of these components. You can double-check by ensuring that there are no imports in this le that start with mx.controls. 8 Save this class. It should compile successfully without any errors or warnings. Creating the Skin Yo u n o w h a v e a c o m p o n e n t w a i t i n g t o b e s k i n n e d . I t h a s t h e r e q u i r e d s k i n p a r t s a n d t h e s k i n states dened. In this section, you will create a skin for the new component and apply it so that you can run the application and see some initial results. 1 Right-click the skins folder and choose New > MXML Skin from the pop-up menu. 2 Name the new skin ShoppingListSkin. Click Browse next to the Host component eld and select your ShoppingList component. From the Library of Wow! eBook Download from www.eBookTM.com ptg 441 Creating the Visuals 3 Click Finish and a new skin is created for you. <?xml version=”1.0” encoding=”utf-8”?> <s:Skin xmlns:fx=”http://ns.adobe.com/mxml/2009” xmlns:s=”library://ns.adobe.com/flex/spark” xmlns:mx=”library://ns.adobe.com/flex/mx”> <! host component > <fx:Metadata> [HostComponent(“components.ShoppingList”)] </fx:Metadata> <! states > <s:states> <s:State name=”normal” /> <s:State name=”disabled” /> </s:states> <! SkinParts name=dataGroup, type=spark.components.DataGroup, required=true name=totalLabel, type=spark.components.Label, required=true name=quantityLabel, type=spark.components.Label, required=true name=viewCartBtn, type=spark.components.Button, required=false > </s:Skin> Note that the HostComponent metadata was entered on your behalf, the required skin states were created based on the SkinState metadata in your ShoppingList class, and Flash wrote a comment in the code reminding you of the SkinParts you must have to be considered valid. 4 Just below the comment for the SkinParts, add an <mx:Image/> tag with a source of assets/receipt.png. <mx:Image source=”assets/receipt.png”/> is will load the background image for your new component. Here is a quick reminder of the skin you are about to build: From the Library of Wow! eBook Download from www.eBookTM.com [...]... method, 348 addEventListener() method, 17 7 17 8, 228, 2 71, 45 1 45 5 addItem() method adding ArrayCollections, 19 2 19 3 adding items to shopping cart, 1 54 15 6, 15 7, 282 adding products to lists, 336, 342 checking conditions in, 1 64 16 5 addProductHandler() method, 2 81, 282 AddToCart button, 57, 1 54 15 8, 16 5 AddToCart() method, 1 54 15 8, 18 8, 277–278 Adobe, 11 , 12 Adobe Flash See Flash Adobe Flex See Flex Adobe. .. operations, 45 3 45 5 communicating with events, 45 0 45 3 creating classes, 14 2 , 15 0, 15 3, 43 2 43 5 defining, 43 0 43 7 handling asynchronous operations, 44 5 45 0 overview, 42 6 42 9 refactoring, 43 2 44 4 skins for See skins user interface for, 43 1 uses for, 42 8 43 0 using custom class, 43 5 43 7 ActionScript event handler, 98 1 04 ActionScript Virtual Machine (AVM), 13 addData() method, 337, 339, 346 addElement()... 47 , 52, 54 55, 58–63 acceptDragDrop() method, 338, 3 41 , 345 ActionScript class name caution, 43 9 components See ActionScript components considerations, 42 6 data binding, 87 described, 12 displaying summary data with, 3 21 323 Drawing API, 41 0 41 3 event handling, 96–97 Flash platform and, 11 grouping data with, 311 –3 14 versions, 12 XML class, 1 24 ActionScript 2.0, 1 24 ActionScript 3.0, 12 , 1 24 ActionScript... in, 1 94 19 6 46 7 sorting items in, 18 9 19 3 using cursors in, 1 94 19 6 ArrayList, 18 0, 282 arrays data binding and, 17 9 19 9 filtering items, 19 8 19 9 replacing with ArrayCollections, 18 9 19 3 tracking items with, 15 6 1 64 of validators, 3 74 375 ASDoc (ActionScript and MXML API Reference), 40 , 77, 205, 382 asterisk (*), 372 Asynchronous JavaScript and XML (AJAX), 8–9 asynchronous operations, 12 3, 44 5 45 0... (@), 12 9 AVM (ActionScript Virtual Machine), 13 AVM2, 13 B base classes, 227, 247 , 42 7, 43 1 43 2 base state, 220 [Bindable] metadata tag, 13 3, 14 2 , 17 0 17 5, 17 9 bindings See data binding BitmapImage, 337–338, 40 8 BorderContainer, 47 braces { }, 87, 16 9, 17 2, 1 74, 17 9 brackets [ ], 19 2, 263 Breakpoint Properties view, 40 breakpoints See also debugging conditional, 39 40 ignoring, 38–39 properties, 40 removing,... scrolling content, 48 49 shopping cart See shopping carts skins for See skins states, 216 , 220, 226 styles See styles view states, 63–70, 83–86 web See web applications arguments, 14 4 array notation, 12 8, 18 7, 312 , 322 ArrayCollections, 17 9 19 9 changes to, 285 creating from remote XML data, 18 0 18 7 filtering items in, 19 8 19 9 overview, 17 9 18 0 populating, 18 0 18 7 retrieving data from, 18 7 18 9 searching... Reference (ASDoc), 40 , 77, 205, 382 ActionScript classes See classes ActionScript components, 42 5 45 7 See also components adding functionality to, 44 4 45 5 background image for, 44 1 choosing base class, 43 1 43 2 46 6 Download from www.eBookTM.com From the Library of Wow! eBook Index application files basic elements, 22 creating, 20– 21 default, 22 deleting, 41 naming, 20, 21 organizing, 18 –23 structure of,... components.ShoppingListRenderer 11 Save and run your application You should now have a completely styled custom component What You Have Learned In this lesson, you have: • Learned the concepts of custom ActionScript components (pages 42 6 43 2) • Performed an extensive refactor (pages 43 2 44 4) • Created an ActionScript skinnable component (pages 43 2 44 0, 44 4 45 5) • Created your own skin (pages 44 0 44 4) • Used the Scroller... top to 16 2, color to #0000FF, and fontSize to 11 11 Add another with the id set to totalLabel, right set to 12 , top to 16 2, color to #0000FF, and fontSize to 11 This label will hold the actual formatted total on the shopping cart 12 Finally,... operator), 12 9 $ (dollar sign), 369 = (equal sign), 22 # (hash mark), 397 - (hyphen), 386 # (pound sign), 385 “ (quotation marks), 96 ‘ (quote marks), 96 _ (underscore), 17 5 17 6, 200, 3 34, 43 4 : (colon), 22 (descendant) operator, 13 0 (dot) operator, 12 7 12 8 { } (curly brackets), 87, 16 9, 17 2, 1 74, 17 9 [ ] (square brackets), 19 2, 263 ++ operator, 16 2 ( ) (parentheses), 97–98, 263 A absolute positioning, 47 , . fontSize to 11 . <s:Label text=”Total:” left=”22” top= 16 2” color=”#0000FF” fontSize= 11 ”/> 11 Add another <s:Label/> with the id set to totalLabel, right set to 12 , top to 16 2, color. id. 6 Below the quantityLabel, add a tag pair for <s:Scroller></s:Scroller>. Set the left property to 22, the top property to 30, the width to 14 9 , and the height to 11 5. You will. with an id of divider. Set the left property to 22, the right property to 10 , and the top to 15 5. Inside the tag pair, set the stroke property to an instance of the SolidColorStroke with a

Ngày đăng: 08/08/2014, 20:20

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan