Flex & Flash Builder
lesson 1



               www.dsp-ip.com
‫לפני שנתחיל, אם החומר יעניין אותכם‬
                                    :‫אנא פנו אלינו ל‬
                 ‫•הורדת השקפי...
Rich Internet Applications
• Deeper customer engagement - The focus is on User
  Experience!
• Decreased development costs...
RIA possibilities
•   AJAX (Asynchronous JavaScript and XML)
•   Adobe Flash
•   Adobe Flex 3 (4 is beta)
•   Microsoft Si...
What is Flex?
• Part of a larger concept called Rich Internet Applications
  (RIA)

• A framework developed by Macromedia ...
Flex Demo Sites
•   http://iexpenseonline.com/#
•   http://www.picnik.com/app
•   http://www.pepsi.com/
•   https://custom...
Disadvantages of Flex
• Using Flex is easy…. But using it correctly…NOT!
  Flex application can have huge bottle necks and...
Flex Application LifeCycle
•   Application is created using Flex Builder
•   Application is compiled using MXMLC to swf
• ...
Markup + Code
• Using Markup (XML) is not sufficient for software
  development.. However, using code alone can be quite
 ...
Roles division
MXML
• Layouting!!!!
• Effects
• States
• Declarations and bindings
• Transitions
• More…

AS
• All the res...
Meaning of Attributes in MXML
• XML attributes have a certain syntax. name=“value”
• In MXML(XML) the attributes are used ...
Anatomy of Flex Application
•   Application file (Usually MXML)
•   .AS files (Classes, packages, include files)
•   .MXML...
Directory Structure
• src (not mandatory)
   ▫ All code tree begins here
• bin-debug
   ▫ Compiled swfs + unembedded asset...
Anatomy of MXML File
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
       xmlns:mx="http://www.adobe.com/2006/mxm...
SWC – Flex Library
• Flex’s equivalent to Java’s JAR
• SWC is a collection of compiled classes (swf) + manifest
  file…
• ...
The Working Environment
•   Browser
•   Media authoring software
•   SDK
•   Flash Player with debugging capabilites for y...
Flex SDK
• http://opensource.adobe.com/wiki/display/flexsdk/Dow
  nload+Flex+3
• Open source and Propriety versions

• The...
Flex SDK Structure
• bin-
   ▫ mxmlc.exe (create swf)
   ▫ asdoc.exe (create doc)
   ▫ compc.exe(create swc)
• lib- jar li...
Flex Reference
• http://livedocs.adobe.com/flex/3/langref/index.html




       Fast Forward Your Development       www.ds...
Flash Player Debugger
• http://www.adobe.com/support/flashplayer/downloads.
  html
• Crucial for debugging
• Can be annoyi...
Flex Builder IDE
• Eclipse Plugin , can be integrated with other eclipse
  plugins (SVN, etc)
• Comes in 2 forms:
  ▫ Stan...
Flex Builder IDE - Disadvantages
•   Slow…
•   Memory hogging
•   Crashes a lot….
•   Weird bugs….




         Fast Forwa...
Orientation
• Perspectives
• Workspaces
• Projects
  ▫ Importing projects
  ▫ New project wizard
• New file wizard
• Sourc...
Useful features
• Project Properties
  ▫ Flex Compiler
       Update SDK dialog
       Wrapper settings
       Additional ...
Fast Forward Your Development   www.dsp-ip.com
ActionScript3




                www.dsp-ip.com
Introduction
• AS3 has evovled from AS1,2 used in earlier flash players.
• AS1,3 where not really OO languages (Object Ori...
Introduction
• AS3 has a built-in support for XML and implementation
  of E4X for VERY easy manipulations on XML data

• A...
AS3 and Flex
• AS3 is the programming language driving Flex
• All MXML code is translated by Flex to AS3 and
  everything ...
Conventions
• Remarks-
  ▫ // This is commented
  ▫ /* This is also commented */
• String delimiters- either ‘ or “

• One...
Reserved Keywords
•   import,package, class, this, super ,extends,
•   interface, implements
•   try, catch, finally, thro...
OOP in AS3
•   Ineritance – extends
•   Call to superclass’ constructor – super();
•   Call to superclass’ method – super....
OOP in AS3 - Packages
•   Packages- organizational structures to hold classes.
•   Package hierarchy levels are separated ...
OOP in AS3 - Import
• The AS ‘import’ statement allows usage of the imported
  package function.
• To use classes in the u...
OOP in AS3 – Package Functions
• In AS3, packages also hold namespaces and functions.
• Package functions are functions wh...
MXMLC Restrictions
Limitations
• Every AS file must have exactly one externally
  visible(internal/public) definition with...
MXMLC Restrictions - Examples
//File: demo/Screen1.as
package demo
{
   class Screen1 implements Screen
   {
       //code...
Access Modifiers

The default modifier is ‘internal’!




        Fast Forward Your Development   www.dsp-ip.com
AS3 Native Classes
•   int, uint, Number
•   Boolean
•   String                     Support Automatic Conversion
•   Date
...
Variable Instantiation
 • All variables support instantiation with the ‘new’ opeator

 • Some of the native variables supp...
Static Variables
• Variables which are defined inside a class and belong to
  the class and not to it’s instances.
• Stati...
Casting
• Using the () operator or using the ‘as’ operator. The first
  method will return error if needed and it is there...
Special Types and Values
     Value        Description
     void         Marks that a function does not
                  ...
Getters and Setters
class Meat
{
 private var _animal:String;
 private var _tasty:Boolean;
 private var _fatty:Boolean;
  ...
Constructors
• Constructors must be marked ‘public’
• Constructor name must match the class name

• There are no destructo...
Constructors
• Only the MINIMAL amount of code should be in the
  constructors because they are NOT jitted      i.e. they ...
Constructors and MXML Syntax
package components
{
import mx.controls.Button;
import mx.events.FlexEvent;

    public class...
Dynamic Programming
• AS3 supports has both dynamic and static capabilities
• Dynamic programming is the capability to add...
Objects
• All Flex’s classes are based on the object class.
• Objects in Flex are implementations of dynamic map
  with st...
Operators – delete
Can be used for several similar functions:

• Objects – remove dynamic property
• Array – remove elemen...
Operators- The strict equality
• == is the equality operator (!= is the not equal)
• === is the strict equality operator (...
Automatic Conversion
• To Number:
  ▫ undefined=> NaN
  ▫ null=>0, empty string=> 0, Object,string=> 0
  ▫ true=>1, false=...
Automatic Conversion
• To Boolean:
  ▫ Empty string, 0 ,null, NaN, undefined => false
  ▫ All the rest => true

• To strin...
Operators - ./[] syntax
• Accessing a property of an object/ child within a XML
  can be performed by using the ‘.’ or the...
Operators – instanceof, is, as
• instanceof is deprecated….
• Use ‘is’ to check for type of variable in order to prevent
 ...
Operators – for-in , for-each-in


var arr:Array=[];
arr[3]="test string";
arr[7]="demo string";
for (var iter:String in a...
Operators - … operator
    • Used to declare that a function can accept any number of
      parameters of any type.
    • ...
Strings
• Flex supports Unicode/UTF8 and a very good support for
  localization
• The String class has many useful methods...
Arrays
• Arrays in AS3 are implemented in a very flexible method.
• Arrays are a dynamic entity which can be used in sever...
Arrays
• First element is number 0
• ‘length’ property equals the last index entered +1!!!
• Useful functions
   ▫ push, p...
Examples
• TestAS3
• TestStringArrays




       Fast Forward Your Development   www.dsp-ip.com
Flex Goodies




               www.dsp-ip.com
Data Binding
• Data binding is a Flex mechanism in charge of updating
  all variables marked as binded to a certain variab...
Data Binding How to
• Marking the source
  ▫ Only needed in AS
  ▫ Source can be either getter or property
  ▫ Usage of th...
Data Binding How to
• If several <mx:Binding> point to the same destination.
  All will work and the last one which operat...
When does Data Binding Occur
Data binding updates can occur on three occasions:

1. Initialization of a component
2. Anyti...
How does it work???
• The usage is simple.. The implementation behind the
  scenes is trickier..

• The [Bindable] metadat...
mx.binding.utils.BindingUtils
 • This class include two static methods which allow the
   creation of binding in AS:
   ▫ ...
Conditional Binding
• Usage of the [Bindable(event=“eventName”] metadata,
  cancels the !== comparison and delegates the
 ...
When to use binding

• Binding fields in components in the view to the model

• Binding ‘currentState’ property of a UICom...
Callbacks
• Major part of working with flex, is wise usage of callbacks
  and events.
• Callbacks are placeholders on Flex...
Callbacks - Example

private function toUpperCallback(element:*, index:int,
                                 arr:Array):St...
MetaData
• Metadata tags provide information to the Flex compiler.
• Metadata are like Annotations in Java
• Metadata tags...
Common Metadata
• [Bindable]
• [ArrayElementType]
• [Event]

Will be discussed later in this course-
• [RemoteClass]
• [St...
[Inspectable]
[Inspectable(category="general",enumeration="wide,narrow,node")]
public function set property(str:String):vo...
[Embed] – Embedding of Assets
 • Embedding is inserting an external file to a swf file.
 • “Everything” can be embedded in...
Embeding Using CSS
• It is a bad practice to embed assets directly to your main
  swf. The solution is to use the embed me...
Examples
• AppCallbacks.mxml
• AppBinding.mxml
• AppEmbeding.mxml




      Fast Forward Your Development   www.dsp-ip.com
? ‫היה מעניין‬
                                           :‫פנו אלינו ל‬
                   ‫•הורדת השקפים לשעור זה - חינם...
Upcoming SlideShare
Loading in...5
×

Flex lesson 1

1,458

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,458
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Flex lesson 1

  1. 1. Flex & Flash Builder lesson 1 www.dsp-ip.com
  2. 2. ‫לפני שנתחיל, אם החומר יעניין אותכם‬ :‫אנא פנו אלינו ל‬ ‫•הורדת השקפים לשעור זה - חינם‬ ‫•קבלת שעורי בית ופתרון להשוואה – חינם‬ http://bit.ly/91z7xk FLEX ‫•קבלת פרטים על לימודי‬ ‫ או‬www.dsp-ip.com ‫ניתן להשאיר פרטים באתר‬ ‫או לפנות לעדי‬ Adi Yakov Training Manager www.dsp-ip. www.dsp-ip.com adi@dsp- adi@dsp-ip.com Mail : info@dsp-ip.com info@dsp-ip. 09-8651933, 09-8850956 8651933, 09- Phone: 972- 8850956, Phone: +972-9-8850956, Fax : 050- 8962910 50- Fast Forward Your Development www.dsp-ip.com
  3. 3. Rich Internet Applications • Deeper customer engagement - The focus is on User Experience! • Decreased development costs (Cross browser testing = 20% of total development time) • Simple installation and execution…runs everywhere • As rich a display as any desktop Application (3d, etc) • Fit Internet and intranets.. • Fit almost any type of application • Live within the browser Fast Forward Your Development www.dsp-ip.com
  4. 4. RIA possibilities • AJAX (Asynchronous JavaScript and XML) • Adobe Flash • Adobe Flex 3 (4 is beta) • Microsoft Silverlight 3 • JavaFX 1+ • HTML 5? Fast Forward Your Development www.dsp-ip.com
  5. 5. What is Flex? • Part of a larger concept called Rich Internet Applications (RIA) • A framework developed by Macromedia (Adobe) on the basis of the very successful Flash technology (Virtual machine, players/ bytecode SWF, etc) • A software creation platform based on the states/views paradigm (and not the animation/timeline pardigm of Flash authoring) Flex gives you the best of both worlds… Fast Forward Your Development www.dsp-ip.com
  6. 6. Flex Demo Sites • http://iexpenseonline.com/# • http://www.picnik.com/app • http://www.pepsi.com/ • https://customizer.harley-davidson.com/GMA_customizer.jsp • http://www.scrapblog.com/ • http://gpsmission.com/gps-mission/missionadmin/create.do • http://www.buildyourhonda.eu/ Fast Forward Your Development www.dsp-ip.com
  7. 7. Disadvantages of Flex • Using Flex is easy…. But using it correctly…NOT! Flex application can have huge bottle necks and very poor performance… Proper usage of flex demands understanding of the work of the AVM (ActionScript Virtual Machine) and deep acquaintance with it’s Flex’s mechanisms • Flex application is a lot heavier than regular flash swf • Flex is propriety • Flex compiler is SLOW! Fast Forward Your Development www.dsp-ip.com
  8. 8. Flex Application LifeCycle • Application is created using Flex Builder • Application is compiled using MXMLC to swf • SWF are stored on server.. • A link to the swf is embedded within a HTML page • User surfs to the page, the swf is downloaded to cache • The local (browser plugin) flash player , executes the application • Application can open http session to the server and request data/content (SOAP/REST/BINARY) Fast Forward Your Development www.dsp-ip.com
  9. 9. Markup + Code • Using Markup (XML) is not sufficient for software development.. However, using code alone can be quite cumbersome for simple tasks (of which there are plenty) • The idea of combining to languages/syntaxes to create an application is not new to flex and it is derived from the HTML + JavaScript (Ajax) duo. • In flex the combination is composed of : ▫ MXML - declarative ▫ AS - programming • In Silverlight this idea was implemented as XAML+C# Fast Forward Your Development www.dsp-ip.com
  10. 10. Roles division MXML • Layouting!!!! • Effects • States • Declarations and bindings • Transitions • More… AS • All the rest Fast Forward Your Development www.dsp-ip.com
  11. 11. Meaning of Attributes in MXML • XML attributes have a certain syntax. name=“value” • In MXML(XML) the attributes are used to pass values to the component. • The attributes can represent several different things in the component: ▫ Properties ▫ Event listeners ▫ Styles • You should check (in the beginning) the reference to know the exact type of each attribute and what value to pass. Fast Forward Your Development www.dsp-ip.com
  12. 12. Anatomy of Flex Application • Application file (Usually MXML) • .AS files (Classes, packages, include files) • .MXML* files • Assets (files, images, audio, video, etc) • CSS • Included SWC’s • XML data • HTML Wrapper Fast Forward Your Development www.dsp-ip.com
  13. 13. Directory Structure • src (not mandatory) ▫ All code tree begins here • bin-debug ▫ Compiled swfs + unembedded assets + HTML wrapper • bin-release (same as bin-debug) ▫ Used when picking export for release • libs ▫ Default include directory for swc’s • html-template ▫ AC_OETags.js – Flash player detection code ▫ Index.template.html – template to generate wrapper ▫ playerProductInstall.swf – flash version updates Fast Forward Your Development www.dsp-ip.com
  14. 14. Anatomy of MXML File <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:components="components.*" layout="vertical" > <mx:Script> <![CDATA[ private var txt:String= "Hmmm..."; ]]> </mx:Script> <components:MyCanvas width="100%" height="100%"> <components:MyTextArea id="ta"/> </components:MyCanvas> </mx:Application> Fast Forward Your Development www.dsp-ip.com
  15. 15. SWC – Flex Library • Flex’s equivalent to Java’s JAR • SWC is a collection of compiled classes (swf) + manifest file… • Created using the compc.exe tool in the SDK bin directory • The swc is placed in the include directory (default is libs) of the application and its content can be accessed by using import statement Fast Forward Your Development www.dsp-ip.com
  16. 16. The Working Environment • Browser • Media authoring software • SDK • Flash Player with debugging capabilites for your browser • Flex Builder IDE (Eclipse) • Server side- AMF Gateway Fast Forward Your Development www.dsp-ip.com
  17. 17. Flex SDK • http://opensource.adobe.com/wiki/display/flexsdk/Dow nload+Flex+3 • Open source and Propriety versions • The SDK is a work in progress, therefore, it is recommended to keep 2-3 different versions and recompile the project if any weird/untraceable to your code errors occur Fast Forward Your Development www.dsp-ip.com
  18. 18. Flex SDK Structure • bin- ▫ mxmlc.exe (create swf) ▫ asdoc.exe (create doc) ▫ compc.exe(create swc) • lib- jar libraries for the compiler • frameworks- the flex packages • asdoc- tools needed to create ASDOC (like JavaDoc) • runtimes- flash and AIR player for Win/Mac Fast Forward Your Development www.dsp-ip.com
  19. 19. Flex Reference • http://livedocs.adobe.com/flex/3/langref/index.html Fast Forward Your Development www.dsp-ip.com
  20. 20. Flash Player Debugger • http://www.adobe.com/support/flashplayer/downloads. html • Crucial for debugging • Can be annoying , therefore it is recommended to install it only on the browser used for developing… Fast Forward Your Development www.dsp-ip.com
  21. 21. Flex Builder IDE • Eclipse Plugin , can be integrated with other eclipse plugins (SVN, etc) • Comes in 2 forms: ▫ Standalone – stripped eclipse + plugin ▫ Plugin • Supports all needed formats (CSS, MXML, AS) • Code completion, type checking • Code profiling options • WYSIWYG (“Design View”) MXML Editor • WYSIWYG (“Design View”) CSS Editor Fast Forward Your Development www.dsp-ip.com
  22. 22. Flex Builder IDE - Disadvantages • Slow… • Memory hogging • Crashes a lot…. • Weird bugs…. Fast Forward Your Development www.dsp-ip.com
  23. 23. Orientation • Perspectives • Workspaces • Projects ▫ Importing projects ▫ New project wizard • New file wizard • Source View • Design View • Debugger perspective Fast Forward Your Development www.dsp-ip.com
  24. 24. Useful features • Project Properties ▫ Flex Compiler Update SDK dialog Wrapper settings Additional compiler arguments • Configuration files ▫ .project (Eclipse Builder directives) ▫ .actionScriptProperties (Most of the project properties) ▫ .flexProperties (Rest of the project properties) Fast Forward Your Development www.dsp-ip.com
  25. 25. Fast Forward Your Development www.dsp-ip.com
  26. 26. ActionScript3 www.dsp-ip.com
  27. 27. Introduction • AS3 has evovled from AS1,2 used in earlier flash players. • AS1,3 where not really OO languages (Object Oriented) AS3 includes full OOP capabilities but also provides some backward portability • AS3 is exectued on the ActionScript Virtual Machine 2 (AVM2) which is part of the flash player and AIR player • AS3 code compiled into byte code and jitted (will be discussed later on the course) • This entire execution environment is single-threaded Compiled AS3 code is saved as SWF or SWC files Fast Forward Your Development www.dsp-ip.com
  28. 28. Introduction • AS3 has a built-in support for XML and implementation of E4X for VERY easy manipulations on XML data • AS3 has a built-in support for Regular expressions • AS3 supports an extensive and event model based on DOM level 3 events spec. • AS3 is similar in structure/syntax to Java/C# Fast Forward Your Development www.dsp-ip.com
  29. 29. AS3 and Flex • AS3 is the programming language driving Flex • All MXML code is translated by Flex to AS3 and everything is compiled together • AS3 syntax can be used in several places: ▫ Separate AS files (include files) ▫ Separate class AS files ▫ Inside <mx:Script> tags in MXML file ▫ Inside binding expressions Fast Forward Your Development www.dsp-ip.com
  30. 30. Conventions • Remarks- ▫ // This is commented ▫ /* This is also commented */ • String delimiters- either ‘ or “ • One-line commands do not have to end with ; • Every AS code inside MXML file must be wrapped with CDATA Fast Forward Your Development www.dsp-ip.com
  31. 31. Reserved Keywords • import,package, class, this, super ,extends, • interface, implements • try, catch, finally, throw • switch, case, break, default, continue • const, var, return, static, new, is, as, delete • public, private, protected, internal • true, false, void, *, null, undefined • do, while, for , in, each, if, else • use, namespace • with, to • override, function, get, set • native, dynamic • include Fast Forward Your Development www.dsp-ip.com
  32. 32. OOP in AS3 • Ineritance – extends • Call to superclass’ constructor – super(); • Call to superclass’ method – super.methodName(); • Preventing inertiance – final on a class • Overriding – override • Preventing overriding – final on a function • Implementation of interfaces – implements • No abstract classes! • No function overloading! • ‘this’ is supported but usually not needed Fast Forward Your Development www.dsp-ip.com
  33. 33. OOP in AS3 - Packages • Packages- organizational structures to hold classes. • Package hierarchy levels are separated by ‘.’ • The unnamed package is the default package • AS file should begin with a package declaration which EXACTLY correlates with its relative path. • MXML file does not have package definition. The package is derived from the relative path Fast Forward Your Development www.dsp-ip.com
  34. 34. OOP in AS3 - Import • The AS ‘import’ statement allows usage of the imported package function. • To use classes in the unnamed package you do not need to use ‘import’ • In MXML there is no ‘import’ statement and the same function is achieved using ‘xmlns’ attribute <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:components="components.*"> <components:MyCanvas/> </mx:Application> // MyCanvas is at components/MyCanvas.mxml Fast Forward Your Development www.dsp-ip.com
  35. 35. OOP in AS3 – Package Functions • In AS3, packages also hold namespaces and functions. • Package functions are functions which are defined in a separate AS file inside a certain packge. • These functions do not belong to any class. • In order to use package functions , ‘import’ is needed • Package functions are a remainder from earlier versions of AS.. But can also be useful if you have package that needs 1-2 functions and you do not want it to be static functions within a class in the package //File: demo/beginscreen.as package demo { public function beginscreen(os:int):int { //code here } } Fast Forward Your Development www.dsp-ip.com
  36. 36. MXMLC Restrictions Limitations • Every AS file must have exactly one externally visible(internal/public) definition within a package statement. • An ActionScript source file’s name must match the name of its sole externally visible definition Solution Each “package-level” function or a namespace must be defined internal or public in a separate .as file with a matching file name Fast Forward Your Development www.dsp-ip.com
  37. 37. MXMLC Restrictions - Examples //File: demo/Screen1.as package demo { class Screen1 implements Screen { //code here } } //File: demo/Screen.as package demo { interface Screen { //code here } } //File: demo/beginscreen.as package demo { public function beginscreen(os:int):int { //code here } } Fast Forward Your Development www.dsp-ip.com
  38. 38. Access Modifiers The default modifier is ‘internal’! Fast Forward Your Development www.dsp-ip.com
  39. 39. AS3 Native Classes • int, uint, Number • Boolean • String Support Automatic Conversion • Date • Error • XML • RegExp • Array • Function • Object Fast Forward Your Development www.dsp-ip.com
  40. 40. Variable Instantiation • All variables support instantiation with the ‘new’ opeator • Some of the native variables support literal instantiation by usage of certain operators. This method is faster that instantiation with ‘new’ var btn:Button = new Button(); var xml:XML= <gallery><item price="1" name="abc"/></gallery>; var obj:Object= {label:'Jeans',price:20,discount:false}; var str:String ="Welcome to AS3"; var arr:Array = ['welcome','to','as3']; Fast Forward Your Development www.dsp-ip.com
  41. 41. Static Variables • Variables which are defined inside a class and belong to the class and not to it’s instances. • Static variables are NOT inherited. • Static variables have limitations on binding (Discussed later..) • Static variables are access using their Class name. public static const NUM_OF_REPETITIONS:int=3; public static var counter:int; public static function myFunc(a:Object):void {} Fast Forward Your Development www.dsp-ip.com
  42. 42. Casting • Using the () operator or using the ‘as’ operator. The first method will return error if needed and it is therefore the preferred method. • For the native classes- Date, Array. You must use the ‘as’ operator and CAN NOT use the () operator. • It is recommended to check possibility of casting beforehand using the ‘is’ operator var mydate:Date = obj as Date; var myarray:Array = obj as Array; Fast Forward Your Development www.dsp-ip.com
  43. 43. Special Types and Values Value Description void Marks that a function does not return any value null Marks lack of value undefined Marks an empty place as a result of a delete operation Type Description * untyped. When using dynamic programming this is what is created Fast Forward Your Development www.dsp-ip.com
  44. 44. Getters and Setters class Meat { private var _animal:String; private var _tasty:Boolean; private var _fatty:Boolean; public function Meat (animal:String, tasty:Boolean = true, fatty:Boolean=true) { _animal = animal; _tasty = tasty; } public function set tasty (value:Boolean):void { _tasty=value;} public function get tasty():Boolean {return _tasty;} } var steak:Meat = new Meat("Chicken",true,false); steak.tasty=false; Fast Forward Your Development www.dsp-ip.com
  45. 45. Constructors • Constructors must be marked ‘public’ • Constructor name must match the class name • There are no destructors in AS3. • If inheriting, a call to super() is recommened. • Flex will create a default container if you do not.. Fast Forward Your Development www.dsp-ip.com
  46. 46. Constructors • Only the MINIMAL amount of code should be in the constructors because they are NOT jitted i.e. they are much slower. • In constructors of object which will be displayed on screen , you only assign some basic values and attach event listeners…All other code is postponed to a later stage (other functions). • There are no constructors in MXML classes. • If you want to create AS class which can be used in MXML syntax and decide to use constructor , the constructor should be with zero arguments. Fast Forward Your Development www.dsp-ip.com
  47. 47. Constructors and MXML Syntax package components { import mx.controls.Button; import mx.events.FlexEvent; public class MyButton extends Button { public function MyButton() { super(); this.addEventListener(FlexEvent.INITIALIZE,init); } private function init():void { //the initialization code is postponed to here... } } } Fast Forward Your Development www.dsp-ip.com
  48. 48. Dynamic Programming • AS3 supports has both dynamic and static capabilities • Dynamic programming is the capability to add variables/methods to objects at RUNTIME • All dynamically added instance variables are untyped (*) and public Limitations- • Class’s own content marked private/protected CAN NOT BE ACCESSED in dynamic methods • When inheriting from a dynamic class. You must add ‘dynamic’ to preserve this quality • Dynamic programming is SLOWER than static. Fast Forward Your Development www.dsp-ip.com
  49. 49. Objects • All Flex’s classes are based on the object class. • Objects in Flex are implementations of dynamic map with strings used as keys • In order to use an object as a key, you can use the built-in Dictionary class. var obj:Object={}; obj.stam="stam string"; obj.demo="string to demo"; delete obj.demo; Fast Forward Your Development www.dsp-ip.com
  50. 50. Operators – delete Can be used for several similar functions: • Objects – remove dynamic property • Array – remove element • XML – remove attribute/nodes according to E4X expression Fast Forward Your Development www.dsp-ip.com
  51. 51. Operators- The strict equality • == is the equality operator (!= is the not equal) • === is the strict equality operator (!==) • The difference is that when comparing two native classes using regular == , automatic conversion is performed. This means that (“3”==3) yields ‘true’ • Strict equality does not cause automatic conversion and therefore will result ‘false’ for the same comparison. • Strict equality is faster Fast Forward Your Development www.dsp-ip.com
  52. 52. Automatic Conversion • To Number: ▫ undefined=> NaN ▫ null=>0, empty string=> 0, Object,string=> 0 ▫ true=>1, false=>0 ▫ int, uint, numeric string=> number • To int: ▫ numeric string=> number ▫ undefined=> 0, null=>0 ,Object, all strings=> 0 ▫ true=>1, false=>0 Fast Forward Your Development www.dsp-ip.com
  53. 53. Automatic Conversion • To Boolean: ▫ Empty string, 0 ,null, NaN, undefined => false ▫ All the rest => true • To string: ▫ Object=> the result of toString() ▫ All the rest => String representation (i.e. null->”null”) Fast Forward Your Development www.dsp-ip.com
  54. 54. Operators - ./[] syntax • Accessing a property of an object/ child within a XML can be performed by using the ‘.’ or the [] operators. • The [] operator can also be used for initialization and manipulation of arrays a['flex']='The best'; trace(a.flex);// the best Fast Forward Your Development www.dsp-ip.com
  55. 55. Operators – instanceof, is, as • instanceof is deprecated…. • Use ‘is’ to check for type of variable in order to prevent errors in casting. if (obj is String) i=String(obj).indexOf('flex') else if (obj is Number) i=0 else //do something Fast Forward Your Development www.dsp-ip.com
  56. 56. Operators – for-in , for-each-in var arr:Array=[]; arr[3]="test string"; arr[7]="demo string"; for (var iter:String in arr) trace(iter); //output 3,7 for each (var striter:String in arr) trace(striter); // output 'test string' , 'demo string' Fast Forward Your Development www.dsp-ip.com
  57. 57. Operators - … operator • Used to declare that a function can accept any number of parameters of any type. • Inside the function , you treat the arguments as an array public function getSum(...numbers):Number { var total:Number = 0; for (var i:int = 0; i < numbers.length; i++) total += numbers [i]; return total; } Fast Forward Your Development www.dsp-ip.com
  58. 58. Strings • Flex supports Unicode/UTF8 and a very good support for localization • The String class has many useful methods: ▫ indexOf, lastIndexOf, ▫ slice, split , substr, substring ▫ toUpperCase/toLocaleUpperCase ▫ toLowerCase/toLocaleLowerCase • Some String methods can accepts strings and regular expressions as arguments ▫ match, replace, search Fast Forward Your Development www.dsp-ip.com
  59. 59. Arrays • Arrays in AS3 are implemented in a very flexible method. • Arrays are a dynamic entity which can be used in several forms according to type and continuity indexes: • Numeric Index ▫ Usage like Object (dynamic map with ints as keys) ▫ Usage like regular array with continuous numeric indexes (0,1,2,3…length-1) • String Index (Associative array) ▫ Usage as Object (dynamic map with strings as keys) • Arrays have no type definition Fast Forward Your Development www.dsp-ip.com
  60. 60. Arrays • First element is number 0 • ‘length’ property equals the last index entered +1!!! • Useful functions ▫ push, pop, shift, unshift ▫ splice, concat • Multidimensional arrays are allows without any limitation on sizes/levels. var rowA:Array = [99, 11]; var rowB:Array = [1, 37]; var rowC:Array = [23, 88,99]; var matrix:Array = [rowA, rowB, rowC]; Fast Forward Your Development www.dsp-ip.com
  61. 61. Examples • TestAS3 • TestStringArrays Fast Forward Your Development www.dsp-ip.com
  62. 62. Flex Goodies www.dsp-ip.com
  63. 63. Data Binding • Data binding is a Flex mechanism in charge of updating all variables marked as binded to a certain variable when this certain variable changes. • Data binding is a powerful and flexible mechanism which can make your code a lot simpler to write/maintain • Understanding of the mechanism workings in needed to allow wise usage of data-binding. • The data-binding mechanism is in fact a code generated by the compiler and added to your project Fast Forward Your Development www.dsp-ip.com
  64. 64. Data Binding How to • Marking the source ▫ Only needed in AS ▫ Source can be either getter or property ▫ Usage of the [Bindable] metadata [Bindable]var object1:TextInput • Marking the destination <mx:Label text="{object1.text}"/> ▫ Using {} ▫ Using <mx:Binding> <mx:Binding source="object1.text" destination="object2.text"/> Fast Forward Your Development www.dsp-ip.com
  65. 65. Data Binding How to • If several <mx:Binding> point to the same destination. All will work and the last one which operated will set the value • Binding expressions can be chained (i.e you can bind destination to a source which is also a destination of another binding expression) Fast Forward Your Development www.dsp-ip.com
  66. 66. When does Data Binding Occur Data binding updates can occur on three occasions: 1. Initialization of a component 2. Anytime when the source is changed… 1. newValue!==oldValue in [Bindable] 2. event yyy dispatched in [Bindable(event=“yyy”)] 3. Call to executeBindings()/executeChildBindings() When binding to static sources or to getter w/o setter (read-only property).. The binding will occur only on initialization! Fast Forward Your Development www.dsp-ip.com
  67. 67. How does it work??? • The usage is simple.. The implementation behind the scenes is trickier.. • The [Bindable] metadata is convert to code that dispatches a PropertyChangeEvent when the old value of the source !== new value… • The {} create a ChangeWatcher object that listens for this event and updates the field as needed. • The ChangeWatchers are inside the _watchers array of the component Fast Forward Your Development www.dsp-ip.com
  68. 68. mx.binding.utils.BindingUtils • This class include two static methods which allow the creation of binding in AS: ▫ bindSetter ▫ bindProperty • Dynamic creation of binding is useful for very small set of tasks, such as extending/configuring the binding mechanism… Do not use it instead of the methods described earlier BindingUtils.bindProperty(dest,destProperty, source,sourceProperty); BindingUtils.bindSetter(setter,objectSource,sourceProperty); Fast Forward Your Development www.dsp-ip.com
  69. 69. Conditional Binding • Usage of the [Bindable(event=“eventName”] metadata, cancels the !== comparison and delegates the responsibility for activation of the binding to the programmer. • The binding will be activated when the event mentioned in the metadata will be dispatched public function set useStockName(a:Boolean):void { _useStockNames=a; dispatchEvent("changeUseStockNames"); } [Bindable(event="changeUseStockNames")] public function get useStockNames():Boolean { return _useStockNames; } Fast Forward Your Development www.dsp-ip.com
  70. 70. When to use binding • Binding fields in components in the view to the model • Binding ‘currentState’ property of a UIComponent to an external variable • Binding components ‘dataProvider’ property to a collection • When creating properties (getters/setters) inside your custom components use conditional binding Fast Forward Your Development www.dsp-ip.com
  71. 71. Callbacks • Major part of working with flex, is wise usage of callbacks and events. • Callbacks are placeholders on Flex classes that allow you to ‘plug-in’ your own code (as a function) provided that the function fits a certain signature • Flex exposes many callbacks to the programmer and their usage will be discussed all throughout this course • The following example will present usage of callback function which performs transformation on an array element. Fast Forward Your Development www.dsp-ip.com
  72. 72. Callbacks - Example private function toUpperCallback(element:*, index:int, arr:Array):String { var str:String= String(element); if (str.charAt(0)=='s') return str.toUpperCase() return str; } private function demoMap():void { ta.text="" printArray(arr); printArray(arr.map(toUpperCallback)); } Fast Forward Your Development www.dsp-ip.com
  73. 73. MetaData • Metadata tags provide information to the Flex compiler. • Metadata are like Annotations in Java • Metadata tags are not compiled into swf, but provide information on how to control the way portions of your code are compiled • Metadata tags can reside in either <mx:Script/> or <mx:metaData/> • There are 16 metdata tags in Flex 3.0 • You can create your own (custom) metadata and thus extend the framework to your needs • We will review some of the commonly used metadata Fast Forward Your Development www.dsp-ip.com
  74. 74. Common Metadata • [Bindable] • [ArrayElementType] • [Event] Will be discussed later in this course- • [RemoteClass] • [Style] [Event(name="action1",type="events.MyEvent"] [ArrayElementType("String")] public var arrayOfStrings:Array Fast Forward Your Development www.dsp-ip.com
  75. 75. [Inspectable] [Inspectable(category="general",enumeration="wide,narrow,node")] public function set property(str:String):void { if (str) _property=str; } [Inspectable(category="general",arrayType="String")] [ArrayElementType("String")] public function set arrProperties(arr:Array):void { if (str) _arrProperties=str; } Fast Forward Your Development www.dsp-ip.com
  76. 76. [Embed] – Embedding of Assets • Embedding is inserting an external file to a swf file. • “Everything” can be embedded inside a flex application/module…. (MP3….pictures….programs…) • Flex doesn’t care what is the data that is embedded • Embedding HAS ITS PRICE!!! [Embed(source="../assets/sunset.jpg")] [Bindable] public var sunset:Class; <mx:Image id="pic3" source="@Embed('../assets/sunset.jpg') "/> Fast Forward Your Development www.dsp-ip.com
  77. 77. Embeding Using CSS • It is a bad practice to embed assets directly to your main swf. The solution is to use the embed mechanism inside the css as shown in the following code. • A more detailed examples will be presented on the styling/skinning lessons <mx:Style> Button { upSkin: Embed("assets/box_closed.png"); overSkin: Embed("assets/box.png"); downSkin: Embed("assets/box_new.png"); } </mx:Style> Fast Forward Your Development www.dsp-ip.com
  78. 78. Examples • AppCallbacks.mxml • AppBinding.mxml • AppEmbeding.mxml Fast Forward Your Development www.dsp-ip.com
  79. 79. ? ‫היה מעניין‬ :‫פנו אלינו ל‬ ‫•הורדת השקפים לשעור זה - חינם‬ ‫•קבלת שעורי בית ופתרון להשוואה – חינם‬ http://bit.ly/91z7xk FLEX ‫•קבלת פרטים על לימודי‬ ‫ או‬www.dsp-ip.com ‫ניתן להשאיר פרטים באתר‬ :‫או לפנות לעדי‬ Adi Yakov Training Manager www.dsp-ip. www.dsp-ip.com adi@dsp- adi@dsp-ip.com Mail : info@dsp-ip.com info@dsp-ip. 09-8651933, 09-8850956 8651933, 09- Phone: 972- 8850956, Phone: +972-9-8850956, Fax : +972-50- 8962910 972-50- Fast Forward Your Development www.dsp-ip.com

×