Tuesday, July 31, 2007

Creating Custom Events In Flash AS3 (ActionScript 3)

http://www.8bitrocket.com/newsdisplay.aspx?newspage=5776

Eclipse 3.3: New and Improved

source :here

The highlights are:

* Label coloring for Java elements (enable it in Java > Appearance).
* Quick Access (Ctrl+3) for navigating around to a view or preference page.
* Triple click on a line to select the complete line, drag and drop text. This is very handy when using the mouse, but I am not using the mouse that often in Eclipse though.
* The new Java 6 debugging features rock. Introspecting references is really handy when trying to analyze memory leaks or weird object interactions.
* The Plug-in Development Environment is a lot more advanced. Code completion has become something people expect in Eclipse (it's everywhere), and the new user interface looks very nice.
* Specialized downloads for new users. This makes it a lot easier to try out the new Web Tools or C++ development environment. Just download and unzip, and you are good to go.
* No more mucking around in eclipse.ini to prevent perm space memory errors on Sun JVMs. This is now done automatically on Windows.
* Improved maximizing and minimizing (tiling editors is preserved when maximized) improves reduces the amount of useless whitespace.

Monday, July 30, 2007

Embedding fonts in Flash CS3/AS3

source:http://maohao.wordpress.com/2007/07/29/embedding-fonts-in-flash-cs3as3/

package
{
import flash.display.Sprite;
import flash.text.TextField;import flash.text.Font;
import flash.utils.getDefinitionByName;public class SimpleTextPaneTestDrive01 extends Sprite
{
private static var embeddedFont:Font = null;
public function SimpleTextPaneTestDrive01()
{
var embeddedFontClass:Class = getDefinitionByName(”Font1″) as Class;
Font.registerFont(embeddedFontClass);
var embeddedFontsArray:Array = Font.enumerateFonts(false);
embeddedFont = embeddedFontsArray[0];var fmt:TextFormat = new TextFormat();
//fmt.bold = true;
fmt.color =0xffffff;
fmt.size = 16;//Old day fashion: If you embed it in a textfield on stage
// fmt.font = “Helvetica”;
fmt.font = embeddedFont.fontName;

var tf:TextField = new TextField();
tf.text = “hello world!”;

tf.setTextFormat(fmt);

}

}
}

Saturday, July 28, 2007

composition vs inheritance for Sprite and MovieClip

source

composition vs inheritance for Sprite and MovieClip

a reader recently wrote me with some questions he posted to a newsgroup about inheriting from Sprite in ActionScript 3.0 vs inheriting from MovieClip in ActionScript 2.0. it's an important topic, so i figured i'd post the exchange here, starting with the reader's newsgroup posting:

====
I have been until now a fervent disciple of compositing a graphic instance into a class in every case, rather than making my class extend MovieClip. Admittedly I was a piker at AS2 and only now that I am cranking on AS3 do I consider myself worthy to call myself a beginner OOP programmer. But I bought into all the reasons, and if I were still making AS2 apps, I might remain in that camp.

But lately my devotion has been shaken and now I am seriously considering extending (and then subclassing from) MovieClip or Sprite when making any class which has a visual component. Whereas before I would always compose in a MC instance, almost never make my class inherit from anything but my own superclass, and implement interfaces for polymorphism, now I think I will extend, although still implement interfaces for the usual other reasons. I also still plan to be a composition devotee in all other ways-- I like composition more than inheritance. Also I would not extend MC for classes which have no graphical component, such as game logic components. (I am making games and other interactive entertainment apps, for in-browser distribution.)

Here are a few reasons why my mind is changing; please feel free to refute or support any of these:

--Changes between AS2 and AS3 make the downside of subclassing MC/Sprite smaller than before. I'll let far more informed people come up with good examples, but one seems to be the explicit nature of adding an object to the display list-- the overhead hit of being an MC is small (nonexistent?) if it is not on the list.

"Essential ActionScript 2" advocates composition-- see the large MVC example in which a view class, although nearly entirely visual in function, did not extend MC but rather composited MC. However, in Moock's equally impressive AS3 book, all his examples now seem to use extension. This gives me a new perspective.

--All the Adobe best practices and examples use extension, as do nearly all code samples I see in other helpful forums. I am not one to blindly run with the crowd but I think I'd get better feedback on my code from my peers if I follow suit.

--All the AS3 Flash components seem to use extension, and indeed, AS3 itself is heavily inheritance-based rather than composition-based, for understandable reasons.

I am probably missing a lot and mis-stating much of what is there but hopefully you get the idea.

So once again I ask my better peers: what are now the arguments for and against extending MC or Sprite for one's visually represented classes in AS3? Any observations would be much appreciated.

Also, in Essential ActionScript 2.0 there is an extensive example of the MVC pattern involving, what else, a clock. In his code his Clock view does *not* extend MovieClip (Sprite not having been available in AS2), which is in keeping with his general admonition to compose a graphic element into a class rather than extend one. His view's constructor takes an MC as an argument, and the view attaches its MC instance (which contains all the clock visuals) to the passed MC. The view object is not itself attached, because it is not an MC. The view class contains an MC which ends up getting attached. To change the XY of the view would be to ask the view to change its MC instance's XY. Pure composition.

In Essential ActionScript 3.0 there's an extensive "Virtual Zoo" example which among other things uses an MVC-ish structure, in which the view and controller are the same class. If anything, this would make composing in the view's root graphic element even more sensible than his AS2 example. The View does not really fit the definition "is-a Sprite"; it also is a view manager and controller. But, contrary to his AS2 stance and in keeping with all the other examples in his AS3 book, Moock's view class *extends* Sprite, and is added as a child by the main class. Though the view does happen to contain objects which are also made from Sprite-extending classes (pictures of the zoo animal and the like), the view class does not contain its root sprite the way the AS2 example contained its root MC. The view *is* a Sprite. To change the XY of the view would be to simply set its inherited XY properties from the outside, as any Sprite would be positioned. So though Moock still is a devotee of composition in every other way, on this one point he seems to have decided to use inheritance and take a path different from his AS2 book.

And I have seen most other AS3 code examples follow suit. The Lott AS3 book does, and all the Adobe examples do. So forgive me for having my faith shaken a wee bit.

Though I remain convinced of the rule to favour composition, in this particular set of cases I am considering routinely using inheritance, even though I easily *could* use composition. It just seems to be messier, denser, and longer to use composition *in this set of cases*. So is my reasoning good, faulty, or does it simply betray deep cluelessness about OOP?

====

hi matthew,
as with all design choices in programming, the question of composition vs inheritance comes down to a cost/benefit analysis. in ActionScript 2.0, the only way you could create a logical "type" of display asset was to subclass MovieClip. the cost of implementing MovieClip subclasses was quite high because:

-you had to link a class to a particular .fla
-you had to use arcane syntaxt to create objects (attachMovie())
-the initialization process was messy (no constructor arguments)

i preferred composition over inheritance for MovieClip objects in ActionScript 2.0 partly because the cost of implementing inheritance was so high. the composition alternative sheltered users of my code from those costs.

in ActionScript 3.0, the system for creating a logical "type" of display asset is much cleaner. you simply extend Sprite, and use the subclass like any other class in your program. there's no need to link your class to a movie clip symbol in a .fla (though that's still possible), and you can use normal "new" syntax to create instances, complete with constructor arguments.

so in ActionScript 3.0, the composition approach actually has a higher cost than the inheritance approach because composition requires more code. hence, the cost/benefit question in ActionScript 3.0 is: are the benefits of composition worth the extra code? recall that the benefits of composition are: 1) a more logical class hierarchy, and 2) the ability to extend a logically appropriate class while still using the composed class's functionality.

in simple programs, such as the VirtualZoo, I think composition can be overkill, particularly in the case of the Sprite class. in fact, I would argue that the VirtualPetView can legitimately be thought of as a specialized type of Sprite. conceptually, what is a Sprite? it's a displayable graphic that supports interactivity. what is a VirtualPetView? it's a specific graphic (a pet) that supports a specific type of interactivity (feeding). in other words, VirtualPetView is a specialized type of Sprite, much as a Automobile is a specialized type of Vehicle.

now let's turn to the question of separating the controller from the view in the virtual zoo program. as you point out, VirtualPetView contains both the controller and the view. does that make sense? is the VirtualPetView class becoming bloated and difficult to read? probably a little. if the pet had more interactivity (grooming the pet, teaching it tricks, etc), I think it would be wise to separate input from display. in fact, i even wanted to write a chapter showing the benefits of full mvc by breaking the VirtualPetView into two classes. but at 900 pages and 2 years of writing, a full discussion of mvc was one of the things that got cut from the book.

nevertheless, it's perfectly natural to start with a class that combines the controller and the view, and then later refactor the class to separate the controller from the view. again, for a small program, combining the controller and the view into a single class is less work. as i often say, if the program runs and does what you want it's "right". later, if the program scope increases, you can pay the cost of writing a little more code in exchange for the benefits of greater flexibility and readability.

there are no right answers with this stuff. you have to decide what makes sense for your program. the fact that you are asking these questions means that you are programming the "right" way.

thanks for the interesting question!

colin
Posted by moock at July 28, 2007 08:53 PM

Loading name/value pairs using the mx:HTTPService tag

original author : Peter deHaan

source: Peter deHaan's blog

== quote from his blog ==
<?xml version="1.0" encoding="utf-8"?>

<
mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal" verticalAlign="middle" backgroundColor="white" creationComplete="httpParams.send()">

<
mx:HTTPService resultFormat="flashvars" url="{VARIABLES_URL}" id="httpParams" result="onResult(event)" />

<
mx:Script>

<![
CDATA[
import
mx.rpc.events.ResultEvent;

import
mx.collections.ArrayCollection;

[
Bindable]
private var
VARIABLES_URL:String = "params.txt";

[
Bindable]

private var
paramColl:ArrayCollection = new ArrayCollection();

private function
onResult(evt:ResultEvent):void {

var
vars:Object = evt.result;
var
key:String;

for
(key in vars) {

paramColl.addItem({key:key, value:vars[key]});
}


params.visible = true;
}
]]>
</
mx:Script>

<
mx:VBox>

<
mx:Label text="Parameters:" />
<
mx:DataGrid id="params" dataProvider="{paramColl}" rowCount="5" visible="false">

<
mx:columns>
<
mx:DataGridColumn dataField="key" headerText="Key" />

<
mx:DataGridColumn dataField="value" headerText="Value" />
</
mx:columns>

</
mx:DataGrid>
</
mx:VBox>

</
mx:Application>



Again, I’m sure there is a nicer way of handling the ResultEvent and converting to a data provider, so you may want to play around with it a bit.

Of course, if you know the names of the parameters in the file that you’re loading, you could also just do something like this:

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

<
mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white" creationComplete="httpService.send()">

<
mx:HTTPService id="httpService" resultFormat="flashvars" url="params.txt" />

<
mx:VBox>

<
mx:Label text="name: {httpService.lastResult.name}" />
<
mx:Label text="product: {httpService.lastResult.product}" />

<
mx:Label text="powermove: {httpService.lastResult.powermove}" />
<
mx:Label text="skill: {httpService.lastResult.skill}" />

</
mx:VBox>

</
mx:Application>


Oh, and remember, since the params.txt file is being loaded at run-time and embedded during compile-time, the params.txt file needs to be relative to the SWF file and not the MXML file.

Overview Flex Datagrid Component - Flex Tutorials

source: here

Using the Common UNIX Find Command

source :
http://esofthub.blogspot.com/2007/07/using-common-unix-find-command_07.html

Friday, July 27, 2007

change font size for Microsoft Html Help file (chm)

This may be the way to do it:
1. From the CHM Menu click Options
2. Click Internet Options
3. From Internet Options window click Accessibility button
4. Check box Ignore font styles specified on Web pages
5. Click OK
6. Click Fonts button and select the font you want
7. Click OK

That's it.

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\International\Scripts\3]
"IEFontSize"=hex:02,00,00,00

这里面 IEFontSize 第一位可以取 00、01、02、03 和 04,分别对应 CHM 里面的最小到最大五个层次,02 就是正常尺寸了。
找到键值就好办,上面这段保存成 .reg 文件(注意换行),下次遇到问题导入一下再重开 CHM 字体就正常了。

设置到3就差不多了,4就有字体加粗的感觉了

按住CTRL键
鼠标移到网页上,然后滚动滚轮,就可以调节大小了

Pre-Object Oriented Programming (OOP) for Actionscript

source :
http://polygeek.com/364_adobeflash/actionscript_pre-object-oriented-programming-oop-for-actionscript-part-2

Juggernaut for Flex

source:
http://www.eribium.org/blog/?p=154

Team Project Set

source:
http://nwebb.co.uk/blog/?p=80

== quote ==
Someone I work with has just pointed out the very handy "Team Project Set" option in FlexBuilder (i.e. Eclipse).

We have several Flex Library Projects which work in tandem with our main Flex project. All of these projects are required in order for our main app to compile. All projects are (of course) checked in to SubVersion :]
Now let's say someone new joins the company, or my colleague (who is currently miles away in Berlin) wants to mimic what I have in my FlexBuilder workspace. The easiest option is to create a project set for him.

I can right-click in the Navigator pane of FlexBuilder and select Export -> Team Project Set, then select of all the projects in my workspace which I want to be included in this set and generate a "project set file" (this has a .psf extension).

Now I can send the .psf to whoever wants it. Whoever receives the file (preferably) sets up a brand new workspace first, and then imports the .psf by right-clicking in the Nav pane of Flexbuilder and choosing Import -> Team Project Set

The correct versions of the relevant projects are all checked out of svn/imported in to FlexBuilder for them. Nice.

right click css and compile to swf in FB

source :http://nwebb.co.uk/blog/?p=81

This evening I thought I'd take a look at some of the code behind the fantastic Adobe Flex Store sample application.

If you try to compile the app you may initially get an error because two files are missing (beige.swf and blue.swf) . Never fear, in the readme file it tells you that you can generate the swfs by right-clicking on the corresponding css files and choosing "compile css to swf". I never knew you could do that!

Cairngorm ViewHelpers

http://nwebb.co.uk/blog/?p=84

== quote ==
The use of ViewHelpers in an architectural framework seems to be a bit of a grey area/hotly debated topic ( Jesse Warden summed up both of these things in quite an amusing way some time ago here). I don't have the breadth of knowledge to take one side or another, but I can explain how (and why) we are using them in our current project.

From what I can gather, many people see ViewHelpers as a way to locate, keep track of and simplify the use of Views. The rationale goes like this: when you work on a large project with quite a few people, and the team are creating lots of views, it becomes harder to keep track of the views and what they all do - the ViewLocator makes it easy to locate a particular view (using a descriptive String) and ViewHelpers themselves only expose public methods, thus simplifying working with views for people unfamiliar with the internals of that View.

That's not how we use them here.

Using ViewHelpers To Manipulate Existing Views (Without Updating The Model):
In a simplified view of Cairngorm, the Command class retrieves some info from a DataBase and updates the Model. The View is then updated through bindings to the Model. The Command should not know about the View.

So what happens when you want to do something to the View but you don't want to store anything in the Model? What if you simply wanted to make-visible some text in the View to say that all client-side data was up-to-date? You could set some flag/property in the Model, update that property and get the View to respond, but is that necessarily the right thing to do? Perhaps my simplified example could be better, but there are times where it doesn't feel right to be cluttering up the Model with properties that you don't feel are truly needed or rightly belong in the Model.

Sometimes it seems as if the Command should be able to manipulate the View, yet the Command should know nothing about the View, and you can achieve this with a ViewHelper. The ViewHelper sits in-between the two classes so that the Command and View are no-longer tightly coupled. The Command uses the ViewLocator ( a Singleton) to find the ViewHelper, and calls methods on it which in turn call methods on the View.

Note: To me, the notes in the Cairngorm ViewHelper class sound like they are backing up this as a valid use of ViewHelpers.

Using ViewHelpers When Creating Popups:
Let's say that a user needs to see some information (from a database) in order to make a decision about how many "widgets" to create. You are interested in the user's input (i.e. how many widgets he/she wants to create) but you don't want to store all the retrieved information in your application's Model - you are happy to discard it.

In other words, you want to generate a View (a pop-up window) from a Command. Here is an overview:
The Command would run, retrieve some info from the database and generate a pop-up window. The user would use the data to make a decision about how many widgets to create and enter a value in some input field. When he/she presses the "submit" button on the pop-up window, you remove the pop-up and return the input-value back to the Command. The Command then updates the Model with this value and the main View is updated accordingly via bindings.

Once again, this can be achieved using ViewHelpers without breaking the rule about letting the Command know about the View ( in much the same way as described above).

Using ViewHelpers When Adding Listeners To Popups:
Supposing for a moment that you did let your Command directly create your View... another problem with pop-ups that you may encounter, would be that they probably don't exist at the time you want to add any event-Listeners to it. You can try creating the pop-up first and adding the listeners upon creation, but that's not great.

The ViewHelper is a great place for putting an event-proxy. Extend the class and add the proxy functionality.
Now, rather than the Command listening to the View (which may not even exist, in which case you'll get a "null" error), you listen for events as if they were dispatched from the ViewHelper:
i.e. myViewHelper.addListener ("evtName", someFunc);

One way of coding this could be that when the Command tries to add a listener to the ViewHelper, you take all that info, wrap it up in an object and store it within an array on the ViewHelper.
As soon as the ViewHelper has created the View, it uses that information to add event listeners (between itself and the View). When an event is dispatched from the View it calls the method on the ViewHelper, which in turn calls the corresponding method on the Command class.
Okay, well there are my thoughts on ViewHelpers.
It would be great to hear your opinions (and alternative suggestions) for achieving these types of interactions within a Cairngorm app. Please feel free to leave feedback and add to the already raging debate about ViewHelpers

Conditional visualization in Cairngorm 2.x using the ChangeWatcher class

http://blog.comtaste.com/2007/07/conditional_visualization_in_c_1.html

package ...
{
...

public class MyViewHelper extends ViewHelper
{
private var myChangeWatcher:ChangeWatcher;

public function MyViewHelper() {

myChangeWatcher = ChangeWatcher.watch(MyModelLocator.getInstance(), “myDataSource”, prepareDataProvider);
}


private function prepareDataProvider(event:Event) {

var myAC:ArrayCollection = new ArrayCollection();
for each(var item:Object in MyModelLocator.getInstance().myDataSource) {
//if item satisfies certain conditions
myAC.addItem(item);
}
view.myDataProvider = myAC;
}

}
}

Cairngen 1.2: From 0 to Cairngorm in 10 seconds

http://cairngormdocs.org/blog/?p=31

The Open Source Web Design Toolbox: 100 Web Design Template Sources, Tools and Resources

http://www.designvitality.com/blog/2007/07/the-open-source-web-design-toolbox-100-tools-resources-and-template-sources/

Casting Vs The “as” operator

source :
http://raghuonflex.wordpress.com/2007/07/27/casting-vs-the-as-operator/

== quote ==
Just write a Flex app and try the following in a function

var btn:Button = new Button();

var lst:List = new List();

lst = List (btn);

In short, we are trying to cast a button into a list… What do you expect?? Yes… an RTE (Run Time Error)

It reads

TypeError: Error #1034: Type Coercion failed: cannot convert mx.controls::Button@16ab0479 to mx.controls.List.

There are times in your app development cycle, when you are not sure, if a particular casting is allowed or not. You definitely don’t want to throw an RTE (Run Time Error) to the user either. What you end up doing invariably is using a try…catch block to handle the RTE. A better and cleaner alternative to this is using the as operator

Using the as operator has the following advantages

* It does the exact same thing as casting does, if you are casting between compatible types
* It returns a null if the object cannot be casted to a particular type
* No RTEs :)

Once you use the as operator, you can just do a null check to see if the casting is allowed… as below

var btn:Button = new Button;

var lst:List;

lst = btn as List;

if (! lst) {mx.controls.Alert.show(”Sorry you cant cast it this way”); }

But a word of caution. You cannot use the as operator to cast between types in the Top Level classes (to view them , go to the flex language reference). Which means… Say you want to cast a String to a Number, you cannot do,

num = str as Number;

This gives the following error

Implicit coercion of a value of type Number to an unrelated type String

You’ll have to do the age-old way of casting

num = Number(str);

Hope this is useful… at least to beginners


Responses to “Casting Vs The “as” operator”

1. IanT Says:
July 27th, 2007 at 12:07 pm

As an aside - the other use for ‘as’ is for casting to Array.

Because (for historical reasons, I imagine) this:

var a:Object=[1];
var b:Array=Array(a);

results in b being [[1]] (i.e. the Array() operator creates a new array, instead of casting).

In AS2, this was very difficult to get around. In AS3, just use ‘as’:

var a:Object=[1];
var b:Array=a as Array;

Singleton Factory

source : http://www.bigroom.co.uk/blog/singleton-factory/

== quote ==
package { 

function
Singleton( c:Class ):*
{

for
( var i:String in instances )
{

if
( instances[i].constructor === c )
{

return
instances[i];
}
}


var
obj:* = new c();
instances.push( obj );

return
obj;
}
}

var
instances:Array = new Array();




You can use this function to create an instance of any class (your own or an intrinsic class) as follows (for example):

import flash.geom.Point;
var a:Point = Singleton( Point );

In the comments below, Benny suggested a good improvement to gain a more stable lookup time by using a Dictionary instead of an Array. His suggestion, with minor alterations by me, looks like this.

package {
function Singleton( c:Class ):*
{ return c in instances ? instances[c] : in[c] = new c();
}
}

import flash.utils.Dictionary;
var instances:Dictionary = new Dictionary( false );

Thursday, July 26, 2007

Actionscript 3 Resources

source: here
http://www.kirupa.com/forum/showthread.php?t=223798

http://www.were-here.com/homepage/default.asp

http://www.senocular.com/

other flex framework

http://www.adobe.com/devnet/flex/articles/blueprint.html

http://www.model-glue.com/flex.cfm

http://www.servebox.com/foundry/doku.php

http://www.guasax.com/blog/

http://labs.adobe.com/wiki/index.php/Cairngorm

http://puremvc.org/

http://osflash.org/projects/arp

Cairngorm and SequenceCommand Gotcha

source: here

Another quick post about a gotcha I found when using the SequenceCommand in Cairngorm. I was using an iterator in my command to get a next item and determine if I can use that item or if I need move on to the next...an so on. I had originally decided to just make the nextEvent another event that would run the same command and reuse the logic if I needed to try again. Well since then I had to re-factor the code to work all in one shot since apparently not too far into that sequence of commands I get a stack overflow error. I'm surprised at how quickly it happens since there isn't really much going on. So, I like my re-factored code better anyway and this is a bit of info that you might find useful in the rare occasion you might be thinking about causing a command to basically run itself more than a couple times.

Creating movie clips with reflections in ActionScript 3.0

http://www.adobe.com/devnet/flash/articles/reflect_class_as3.html

Sharing Flex Projects

source:
http://www.rogue-development.com/blog/2007/07/sharing-flex-projects.html

== quote ==
We've got 5 developers all working on the same Flex based project. What's the best way to share the project so everyone can work on it together? (I don't mean a version control system, I mean the actual Flex project).

We tried checking into version control and all using the same .project, .actionscriptProperties, and .flexProperties files, but that was a disaster. Flex likes to open them for read/write and make little modifications at seemingly random times. Then merging changes between developers sucks.

What we do now is each developer creates their own Flex project outside of version control.

Then we link in the src folder of our application into our project. (In eclipse you can make a link to another folder by selecting "new folder" then clicking the advanced checkbox) ... see the picture:

Next, we set that src folder as the default source folder of the project.

Then we delete the .mxml that flex builder auto-created for us when we made the project since we don't need it anymore.

Then we set-as-default application our main mxml file.

We use a few external libraries, so we also add a swc folder under our project's build directory.

It seems to work pretty well. We even have some people using FB2 and some on FB3 using this technique. How do other people handle this?


For those of you following the AgileAgenda progress, two new screenshots of the web-view:
http://www.agileagenda.com/screenshots/screenshot8.JPG
http://www.agileagenda.com/screenshots/screenshot9.JPG

Labels: flex

how do i find the path to where a MC belongs

source 1:
http://www.kirupa.com/forum/showthread.php?p=1935107

Hello :)

in AS3 i don't find a native method ?

For the moment you can test :

package
{

import flash.display.* ;

public class test extends Sprite
{

/**
* Creates a new test instance.
*/
public function test()
{

var container:Sprite = new Sprite() ;

var container2:Sprite = new Sprite() ;
container2.graphics.beginFill(0xFF0000, 1) ;
container2.graphics.drawCircle(0, 0, 150) ;

addChild(container) ;
container.addChild(container2) ;

var target:String = getDisplayPathName(container2) ;

trace( target ) ;

}

static public function getDisplayPathName( display:DisplayObject
):String
{

var parents:Array = [] ;
var parent:* = display ;

while( true )
{
parents.push( parent.name ) ;
parent = parent.parent ;
if (parent.name == null)
{
break ;
}
}

parents.reverse() ;

return parents.join( "." ) ;

}

}

but it's not the better solution lol

eKA+ :)

alternative to mx classes

found in osflash mailing list


The AS3 version of the remoting class in VEGAS :

http://svn1.cvsdude.com/osflash/vegas/AS3/trunk/src/asgard/net/remoting/

With an example :

package
{

import asgard.events.ActionEvent ;
import asgard.events.RemotingEvent ;

import asgard.net.remoting.RemotingService;
import asgard.net.remoting.RemotingAuthentification;

import flash.display.Sprite ;

import test.User ;

public class TestAsgardRemoting extends Sprite
{

// ----o Constructor

public function TestAsgardRemoting()
{

// ----o Register your shared Class.

User.register() ;

// ----o Create Service

var service:RemotingService = new RemotingService() ;

service.addEventListener(RemotingEvent.ERROR, onError) ;
service.addEventListener(RemotingEvent.FAULT, onFault) ;
service.addEventListener(ActionEvent.FINISH, onFinish) ;
service.addEventListener(RemotingEvent.RESULT, onResult) ;
service.addEventListener(ActionEvent.START, onStart) ;
service.addEventListener(RemotingEvent.TIMEOUT, onTimeOut) ;

service.gatewayUrl = "http://localhost/work/vegas/php/gateway.php" ;
service.serviceName = "Test" ;
service.methodName = "getUser" ;
service.params = ["eka", 29, "http://www.ekameleon.net"] ;

// ----o Launch Service

service.trigger() ;

}

// ----o Public Methods

public function onError(e:RemotingEvent):void
{
trace("> " + e.type + " : " + e.code) ;
}

public function onFinish(e:ActionEvent):void
{
trace("> " + e.type) ;
}

public function onFault(e:RemotingEvent):void
{
trace("> " + e.type + " : " + e.getCode() + " :: " + e.getDescription()) ;
}

public function onProgress(e:ActionEvent):void
{
trace("> " + e.type ) ;
}

public function onResult( e:RemotingEvent ):void
{
trace("-----------") ;
trace("> result : " + e.result) ;
trace("-----------") ;
}

public function onStart(e:ActionEvent):void
{
trace("> " + e.type ) ;
}

public function onTimeOut(e:RemotingEvent):void
{
trace("> " + e.type ) ;
}


}
}
More information about this example in my blog in french about the
difference between the classmapping in AS3 and AS2 tutorial :

http://www.ekameleon.net/blog/index.php?2006/08/28/48--amf-class-mapping-difficile-en-as3

Wednesday, July 25, 2007

What's cool in Eclipse 3.3?

source :http://techfeed.net/blog/index.cfm/2007/7/25/Whats-cool-in-Eclipse-33

http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.user/whatsNew/platform_whatsnew.html

Expanded Undo options. You can now undo many more things. From the docs: "When you manipulate projects, folders, or files, you now have the ability to undo and redo the changes you have made. This includes resource creation, deletion, move, copy, and rename." Also: "Undo is now available for many task and bookmark operations. When you create, update, add, or delete a task or bookmark, you now have the ability to undo that change."

Compare editor improvements. Probably my favorite feature in Eclipse is the local history comparison. This is no replacement for a real SCM system, but it does come in handy sometimes. You can even select two different files in your Navigator and compare differences between them. Eclipse 3.3 has some cool improvements to the editor you use to compare/replace between two versions of a file. From the docs: "The contents of compare editors are now kept in sync with other editors currently open on the same file. Comparisons that used to take a long time now take a matter of seconds, thanks to a new text differencing algorithm. Many of your favorite editor commands are now available in compare editors, including find/replace, show whitespace characters, show line numbers, and the Show In sub-menu.

Keys preference page improved. One thing that has always been a pain in the butt is editing shortcut key bindings. It looks like they improved this. In the past, you had to really monkey with it sometimes to get an edited key binding to stick. What I would usually do is add a new one with the key binding I wanted, and then delete the default command that had the key binding I didn't want to use. It appears that you can now just plain edit these, with no more monkey business. :)

Drag/drop files into Eclipse. A long requested and missing feature in Eclipse was the ability to open a file in Eclipse by dragging and dropping it into Eclipse from the file system. This now works.

Spell checking! Source code can now be spell checked, and this feature is enabled by default. However, I'm not seeing this work in CFEclipse...maybe this is something that has to be enabled by the plug-in author?

Text drag/drop. A feature that is often implemented in plug-ins but was not available by default in Eclipse is drag and dropping selected text around your editor. This is now a feature in Eclipse.

Page scrolling. In an editor, hold down control and scroll with the mouse wheel. This will scroll down page at a time, very handy for large amounts of source code in one file.

Oh, and by the way, CFEclipse 1.3.1.5 does support Eclipse 3.3. However, Flex Builder 2 does not support Eclipse 3.3, according to Flex team member Mike Morearty. Flex Builder 3 will run on Eclipse 3.3, however.

Free themes and skins for Flex and AIR

http://scalenine.com/

Migrating to ActionScript 3.0

http://www.adobe.com/devnet/actionscript/#migrating_as3

http://actionscript.codefetch.com/

http://actionscript.codefetch.com/

Tuesday, July 24, 2007

AS3 language 101 for C/C++ coders

source:
http://blogs.adobe.com/kiwi/2006/05/as3_language_101_for_cc_coders_1.html

Run time type checking

Since you can pass things around as anything using the wildcard type (void *), you need a way to check the type of the object at runtime. To do this, you can use the "is" directive:

public function doSomething() : void
{
var something:* = getData();

if (something is String)
{
// handle string logic
}
else
{
// do something else
}
}

This allows for runtime type checking which allows your application to perform different logic depending on what the given object is.

Typecasting

In AS3, think of typecasting like calling the constructor of the type. Functionally, this isn't what happens, but the syntax is what it appears to be doing.

In C: int i = (int)somefloat;
In AS3: var i:int = int(somefloat);

If you see what appears to be something calling the constructor of a class or type but it does not use "new", it's not calling a constructor. It's performing a typecast. For example:

var foo:SomeClass = SomeClass(someObject);
var bar:SomeClass = new SomeClass(someObject);

The first line is typecasting "someObject" into SomeClass. The second line is creating a new SomeClass object, passing "someObject" as a parameter to the constructor. This subtle difference can have wide ranging effects (new object vs. reusing an existing object, etc.). Depending on what the class constructor takes as a parameter, it is possible that both the typecast and the constructor would compile with no errors/warnings in all situations. So, be careful. The difference between a typecast and a new object is just the "new" keyword.

dynamic_cast

In AS3, you will find yourself dealing with interfaces. These are similar in concept to abstract base classes in C++. Objects that implement an interface will be passed around as instances of that interface. So, given an object of a specific interface, how do you get the object as an instance of its subclass? You use the "as" functionality. For example:

var someInterface:ISomeInterface = factory.getSomeInterface();
var someClass:SomeClass = (someInterface as SomeClass);

If "someInterface" is actually an instance of "SomeClass" or a derived class of "SomeClass", the variable "someClass" will be a reference to that object. If "someInterface" is an instance of some other class, the "someClass" variable will be null.

Comments

I just wanted to add one note about the as operator described above in the section titled "dynamic_cast":

The as operator, which is used to cast an object to a type at runtime, can be used not only to cast an instance of an interface (as in the example above) but also to upcast or downcast any type to a possibly related type (i.e. a subclass or superclass). So in the code below, either of the as statements would properly cast the instance:

public class ParentClass {}
public class ChildClass extends ParentClass {}
...
var child1:ChildClass = new ChildClass();
// note this is a ChildClass instance, upcast as ParentClass
var parent1:ParentClass = new ChildClass();
...
var parent2:ParentClass = (child1 as ParentClass);
var child2:ChildClass = (parent1 as ChildClass);

Of course, the second as statement only works because parent1 was declared as ParentClass but instantiated as a ChildClass instance.

For me personally I think of is and as as a pair of related operators; one tells you whether something is an instance of a type, the other one tells you and casts the object all in one operation.

(Sorry about the short note that turned into a long note. I'm sure you already know all of this anyway, but I thought it might not be precisely clear to everyone, based solely on the context of the article.)

In any case, thanks for the articles, and I'm excited to read more!

ActionScript 3.0 Readiness Kit

http://www.unic8.com/en/news/general/actionscript-3.0-readiness-kit.html

actionscriptcheatsheet

download from here

Using An XMLListCollection As A Data Provider and Sorting An XMLListCollection in Flex 2

source : here

Eclipse Keyboard Tricks

source : here
Found these in the Tips and Tricks section of the Workbench User Guide in the help:

Finding a string incrementally
Use Edit > Incremental Find Next (Ctrl+J) or Edit > Incremental Find Previous (Ctrl+Shift+J) to enter the incremental find mode, and start typing the string to match. Matches are found incrementally as you type. The search string is shown in the status line. Press Ctrl+J or Ctrl+Shift+J to go to the next or previous match. Press Enter or Esc to exit incremental find mode.

Go to last edit location
Navigate > Go to Last Edit Location (Ctrl+Q) takes you back to the place where you last made a change. A corresponding button markedᅠ is shown in the toolbar. If this toolbar button does not appear in your perspective, you can add it by selecting Window > Customize Perspective > Other > Editor Navigation.


Shortcuts for manipulating lines
All text editors based on the Eclipse editor framework support editing functions, including moving lines up or down (Alt+Arrow Up and Alt+Arrow Down), copying lines (Ctrl+Alt+Arrow Up and Ctrl+Alt+Arrow Down), inserting a new line above or below the current line (Ctrl+Shift+Enter and Shift+Enter), and converting to lowercase or uppercase (Ctrl+Shift+Y and Ctrl+Shift+X).

getDefinitionByName & AS3 reflection

source: http://www.as3guru.com/?p=5

Actionscript 3: Inspecting classes

source:http://blog.3r1c.net/?cat=14

As you can see here, getQualifiedClassName returns the class name of an Actionscript object. According to livedocs (which put it better than I would have): Any ActionScript value may be passed to this method including all available ActionScript types, object instances, primitive types such as uint, and class objects.

Similarly, getQualifiedSuperclassName returns the base class of the value passed to the method, and adhered to the same rules as getQualifiedClassName.

If you want to go backwards and pass in an actual string representation of a class and get a Class object back, you would want to use getDefinitionByName as I used it above.

To me, the most useful of these methods was the last one 'describeType.' I used this primarily to see if classes implement a certain interface. To keep things abstract a lot of times i will have 'clients' of my components simply pass in Classes to be used as itemRenderers, and will then use Adobe's ClassFactory to create as many instances of this as need be. A lot of these times I will want these classes to be obligated to implement methods, so I will want them to implement a certain Interface. Now, using describeType I can very easily check this at runtime without actually instantiating and using the 'is' operator.

These are some great improvements to Actionscript and a sign that it's really starting to 'grow up.'

component: VerticalTabBar for Flex 2

source :http://www.igorcosta.org/?p=75

Embedded Asset Paths in ActionScript 3

source:http://www.brooksandrus.com/blog/2007/07/23/embedded-asset-paths-in-actionscript-3/

After banging my head against a brick wall for a bit, I finally realized that when embedding assets in ActionScript3 files the path to the embedded asset is relative to the location of the .as file in which the embed statement is placed and not relative to my MXML or AS application entry point. If you look at the image below you’ll note that the embed statement has to traverse up the package structure (3 levels) before pointing to the required graphical asset.

FlexTips - XMLSocket connect() after disconnect from server

source:http://www.franto.com/blog2/flextips-xmlsocket-connect-after-disconnect-from-server

Here is another Flex tips I came across in our project. I don’t know if this was in AS2.0 as well, but in AS3.0 when you receive event that XMLSocket is disconnected (server is disconnected, your net connection is broken), you can’t call xmlsocket.connect() immediately, but you have to wait for a while. So add there Timer(), or call it with function callLater(). It seems it must be called on next frame. I will not upload any example, because I don’t have running test XML server, but I think it is clear what you have to do.

Let me know, if you have similar issue in your projects.

Flex 2.0.1 Hotfix 3 - The WebService Fix

source
http://www.darronschall.com/weblog/archives/000270.cfm

Monday, July 23, 2007

Determining Flash Player version in Flex

To determine which version of Flash Player you are currently using--the standard version or the debugger version--you can use the Capabilities class. This class contains information about Flash Player and the system that it is currently operating on. To determine if you are using the debugger version of Flash Player, you can use the isDebugger property of that class. This property returns a Boolean value: the value is true if the current player is the debugger version of Flash Player and false if it is not.

The following example uses the playerType, version, and isDebugger properties of the Capabilities class to display information about the Player:
<?xml version="1.0"?>

<!--
logging/CheckDebugger.mxml -->
<
mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

<
mx:Script><![CDATA[
import
flash.system.Capabilities;

private function
reportVersion():String {
if
(Capabilities.isDebugger) {

return
"Debugger version of Flash Player";
}
else {
return
"Flash Player";
}
}

private function
reportType():String {

return
Capabilities.playerType + " (" + Capabilities.version + ")";
}
]]></
mx:Script>

<
mx:Label text="{reportVersion()}"/>
<
mx:Label text="{reportType()}"/>

</
mx:Application>


Other properties of the Capabilities class include hasPrinting, os, and language.

Log file location

Log file location
The default log file location changed between the initial Flash Player 9 release and the Flash Player 9 Update. In the initial Flash Player 9 release, the default location is the same directory as the mm.cfg file and you can update the log file location and name through the TraceOutputFileName property. Beginning with the Flash Player 9 Update, you cannot modify the log file location or name and the log file location has changed, as follows:

Windows C:\Documents and Settings\user_name\Application Data\Macromedia\Flash Player\Logs

Macintosh Users/user_name/Library/Preferences/Macromedia/Flash Player/Logs/

Linux home/user_name/macromedia/Flash_Player/Logs/flashlog.txt

Examining linker dependencies

To find ways to reduce SWF file sizes, you can look at the list of ActionScript classes that are linked into your SWF file.

You can generate a report of linker dependencies by setting the link-report compiler option to true. The output of this compiler option is a report that shows linker dependencies in an XML format.

The following example shows the dependencies for the ProgrammaticSkin script as it appears in the linker report:
<script name="C:\flex2sdk\frameworks\libs\framework.swc(        mx/skins/ProgrammaticSkin)" mod="1141055632000" size="5807">

<
def id="mx.skins:ProgrammaticSkin"/>
<
pre id="mx.core:IFlexDisplayObject"/>
<
pre id="mx.styles:IStyleable"/>

<
pre id="mx.managers:ILayoutClient"/>
<
pre id="flash.display:Shape"/>
<
dep id="String"/>

<
dep id="flash.geom:Matrix"/>
<
dep id="mx.core:mx_internal"/>
<
dep id="uint"/>

<
dep id="mx.core:UIComponent"/>
<
dep id="int"/>
<
dep id="Math"/>

<
dep id="Object"/>
<
dep id="Array"/>
<
dep id="mx.core:IStyleClient"/>

<
dep id="Boolean"/>
<
dep id="Number"/>
<
dep id="flash.display:Graphics"/>

</
script>



You can examine the list of prerequisites and dependencies for your application definition. You do this by searching for your application's root MXML file by its name; for example, MyApp.mxml. You might discover that you are linking in some classes inadvertently. When writing code, it is common to make a reference to a class but not actually require that class in your application. That reference causes the referenced class to be linked in, and it also links in all the classes on which the referenced class depends.

If you look through the linker report, you might find that you are linking in a class that is not needed. If you do find an unneeded class, try to identify the linker dependency that is causing the class to be linked in, and try to find a way to rewrite the code to eliminate that dependency.

The linker report

Preventing client-side caching

When you test performance, ensure that you are not serving files from the local cache to Flash Player. Otherwise, this can give false results about download times. Also, during development and testing, you might want to change aspects of the application such as embedded images, but the browser continues to use the old images from your cache.

If the date and time in the If-Modified-Since request header matches the data and time in the Last-Modified response header, the browser loads the SWF file from its cache. Then the server returns the 304 Not Modified message. If the Last-Modified header is more recent, the server returns the SWF file.

You can use the following techniques to disable client-side caching:

Delete the Flex files from the browser's cache after each interaction with your application. Browsers typically store the SWF file and other remote assets in their cache. On Microsoft Internet Explorer, for example, you can delete all the files in c:/Documents and Settings/username/Local Settings/Temporary Internet Files to force a refresh of the files on the next request.
Set the HTTP headers for the SWF file request to prevent caching of the SWF file on the client. The following example shows how to set headers that prevent caching in JSP:// Set Cache-Control to no-cache.
response.setHeader("Cache-Control", "no-cache");
// Prevent proxy caching.
response.setHeader("Pragma", "no-cache");
// Set expiration date to a date in the past.
response.setDateHeader("Expires", 946080000000L); //Approx Jan 1, 2000
// Force always modified.
response.header("Last-Modified", new Date());
Invalidate all items in the client cache by making a change to the flex-config.xml file and saving it. This file stores all the options that the web-tier compiler uses. When the file changes, Adobe Flex Data Services recompiles the application SWF file the next time the MXML file is requested.
Delete the cache.dep file in the /WEB-INF/flex/ directory. This forces the server to invalidate all items in its cache.
Use the Flex Data Services server's caching functionality to control client-side caching. You can set the number of files to cache to 0, which means that Flex Data Services does not cache any files. Every request results in a recompilation. Because the SWF file has a newer data-time stamp, the server sends a new SWF file to the requesting client and the file is never read from the browser's cache. To do this, you set the value of the content-size property in the flex-webtier-config.xml file to 0 as the following example shows:

<cache>
<
content-size>0</content-size>

<
http-maximum-age>1</http-maximum-age>
<
file-watcher-interval>1</file-watcher-interval>

</
cache>


Add the recompile=true query string parameter to your request to force a recompile of the application

disable trace

When you test your applications for performance, ensure that you use the standard version of Flash Player rather than the debugger version of Flash Player, if possible. The debugger version of Player provides support for the trace() method and the Logging API. Using logging or the trace() method can significantly slow player performance, because the player must write log entries to disk while running the application.

If you do use the debugger version of Flash Player, you can disable logging and the trace() method by setting the TraceOutputFileEnable property to 0 in your mm.cfg file. You can keep trace() logging working, but disable the Logging API that you might be using in your application, by setting the logging level of the TraceTarget logging target to NONE, as the following example shows:


myLogger.log(LogEventLevel.NONE, s);

For performance testing, consider writing run-time test results to text components in the application rather than calling the trace() method so that you can use the standard version of Flash Player and not the debugger version of Flash Player.

Creating a localized application

This section begins with a simple sample localized application. It describes the key aspects in creating a localized application.

To build a simple localized application:
1)Create a locale/en_US/RegistrationForm.properties file that contains the following text:registration_title=Registration
submit=Submit Form
personname=Name
street_address=Street Address
city=City
state=State!
zip=ZIP Code
thanks=Thank you for registering!
subtext=[0] alphabetically comes before [1]


The location of the locale directory is not important, but you must be able to add that location to the compiler's source path.

2) Create a locale/es_ES/RegistrationForm.properties file that contains the following text. Ensure that you save this file with UTF-8 encoding.registration_title=Registro
submit=Someta La Forma
personname=Nombre
street_address=Dirección De la Calle
city=Ciudad
state=Estado
zip=Código postal
thanks=¡Gracias por colocarse!
subtext=[0] viene alfabéticamente antes [1]


3) Create a LocalizedForm.mxml application that contains the following code:
<?xml version="1.0"?>

<!--
l10n/LocalizedForm.mxml -->
<
mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<
mx:Script><![CDATA[

import
mx.resources.ResourceBundle;
import
mx.controls.Alert;

[
ResourceBundle("RegistrationForm")]

private static var
rb:ResourceBundle;

private function
registrationComplete():void {

Alert.show(rb.getString('thanks'));
}

]]></
mx:Script>

<
mx:Form>
<
mx:FormItem label="@Resource(key='personname', bundle='RegistrationForm')">
<
mx:TextInput/>

</
mx:FormItem>
<
mx:FormItem label="@Resource(key='street_address', bundle='RegistrationForm')">
<
mx:TextInput/>

</
mx:FormItem>
<
mx:FormItem label="@Resource(key='city', bundle='RegistrationForm')">
<
mx:TextInput/>

</
mx:FormItem>
<
mx:FormItem label="@Resource(key='state', bundle='RegistrationForm')">
<
mx:TextInput/>

</
mx:FormItem>
<
mx:FormItem label="@Resource(key='zip', bundle='RegistrationForm')">
<
mx:TextInput/>

</
mx:FormItem>
</
mx:Form>
<
mx:Button id="b1" label="@Resource(key='submit', bundle='RegistrationForm')" click="registrationComplete()"/>

</
mx:Application>


4)Use the following mxmlc command line to compile the application with the en_US resource bundle:mxmlc -locale en_US source-path+=path_to_locale_dir/{locale} -o Form-us.swf LocalizedForm.mxml

5)Use the following mxmlc command line to compile the application with the es_ES resource bundle:mxmlc -locale es_US source-path+=path_to_locale_dir/{locale} -o Form-es.swf LocalizedForm.mxml

6)Run the two SWF files to see the different form labels and alerts in the applications.

About localized Flex applications

Using Flex, you can write localized applications and access localized components. Flex supports static inclusion of localized resources, but not dynamic retrieval of resources at run time.

Subtopics
About resource bundles and properties files
The localization workflow
About resource bundles and properties files
Resource bundles, or properties files, map keys and values by using simple "key=value" syntax. This is similar to Java properties files; the primary difference from the Java properties format is that you store the Flex properties files as UTF-8 if they contain non-ASCII characters.

The Flex compilers find the properties files the same way that the compilers find other source files. You put the properties files in directories that the compiler searches.

You can access the values in the resource bundles in the following ways:

MXML Use the @Resource directive inside your MXML tags.

ActionScript Use the [ResourceBundle] metadata tag to create an instance of the ResourceBundle class in ActionScript.

In some cases, you must also specify the name of the resource bundle to access the data inside it. The resource bundle in your code uses the same name as the properties file.

The localization workflow
To localize an application, you use the ResourceBundle API. You do this by adding [ResourceBundle] metadata tags in ActionScript or @Resource calls in MXML, creating localized properties files and localization classes and put them into a locale directory, and using the mxmlc compiler to compile the main application.

Optionally, you can package libraries of localized properties files and ActionScript classes in a SWC file that you create with the compc compiler. However, a resource bundle SWC file is necessary only when you are creating a library rather than an application.

layout components

ControlBar layout container:
You use the ControlBar container with a Panel or TitleWindow container to hold components that can be shared by the other children in the Panel or TitleWindow container.

Default size
The height is the default or explicit height of the tallest child, plus the top and bottom padding of the container.

The width is large enough to hold all of its children at the default or explicit width of the children, plus any horizontal gap between the children, plus the left and right padding of the container.

Default padding
10 pixels for the top, bottom, left, and right values.

----------
ApplicationControlBar layout container
You use the ApplicationControlBar container to hold components that provide access to application navigation elements and commands. An ApplicationControlBar container for an editor, for example, could include Button controls for setting the font weight, a ComboBox to select the font, and a MenuBar control to select the edit mode. The ApplicationControlBar is a sublcass of the ControlBar class; however, it has a different look and feel.

Typically, you place an ApplicationControlBar container at the top of the application,

Default size
The height is the default or explicit height of the tallest child, plus the top and bottom padding of the container.

In normal mode, the width is large enough to hold all of its children at the default or explicit width of the children, plus any horizontal gap between the children, plus the left and right padding of the container. In docked mode, the width equals the application width.

If the application is not wide enough to contain all the controls in the ApplicationControlBar container, the bar is clipped.

Default padding
5 pixels for the top value.

4 pixels for the bottom value.

8 pixels for the left and right values.

About data providers and collections

The simplest data provider can be an array of strings or objects; for example, you can use the following code to define a static ComboBox control:

<?xml version="1.0"?>

<
mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<
mx:Script>
<![
CDATA[
[
Bindable]

public var
myArray:Array = ["AL", "AK", "AR"];
]]>

</
mx:Script>
<
mx:ComboBox id="myCB0" dataProvider="{myArray}"/>

</
mx:Application>


However, using a raw data object, such as an Array or Object, as a data provider has limitations:

Raw objects are often not sufficient if you have data that changes, because the control does not receive a notification of any changes to the base object. The control, therefore, does not get updated until it must be redrawn due to other changes in the application or if the data provider is reassigned; at this time, it gets the data again from the updated Array. In the preceding example, if you programmatically add states to the Array, they do not show up in the ComboBox control unless you reassign the control's dataProvider property.
Raw objects do not provide advanced tools for accessing, sorting, or filtering data. For example, if you use an Array as the data provider, you must use the native Adobe Flash Array methods to manipulate the data.
Flex provides a collection mechanism to ensure data synchronization and provide both simpler and more sophisticated data access and manipulation tools. Collections can also provide a consistent interface for accessing and managing data of different types. For more information on collections, see About collections.

Data provider types
The Flex framework supports two basic types of data provider:

Linear or list-based data providers are flat data consisting of some number of objects, each of which has the same structure; they are often one-dimensional Arrays, or objects derived from such Arrays, such as ActionScript object graphs. (You can also use an XMLListCollection object as a linear data provider.)

You can use list-based data providers with all data provider controls, and typically use them for all such controls except Tree and most menu-based control instances. If the data provider contents can change dynamically, you typically use the ArrayCollection class and either the IList or ICollectionView interface methods and properties to represent and manipulate these data providers.

Hierarchical data providers consist of cascading levels of often asymmetrical data. Often, the source of the data is an XML object, but the source can be a generic Object or concrete class. You typically use a hierarchical data providers with Flex controls that are designed to display hierarchical data:

Tree
Menu, MenuBar, and PopUpMenuButton.
You can also extract data from hierarchical data provider to use in controls such as List or DataGrid that take linear data.

A hierarchical data provider defines a data structure that matches the layout of a tree or cascading menu. For example, a tree often has a root node, with one or more branch or leaf child nodes. Each branch node can hold additional child branch or leaf nodes, but a leaf node is an endpoint of the tree.

The Flex hierarchical data controls use data descriptor interfaces to access and manipulate hierarchical data providers, and the Flex framework provides one class, the DefaultDataDescriptor class that implements the required interfaces. If your data provider does not conform to structure required by the default data descriptor, you can create your own data descriptor class that implements the required interfaces.

You can use an ArrayCollection class, XMLListCollection class, ICollectionView interface or IList interface to access and manipulate dynamic hierarchical data.

About the component instantiation life cycle

The component instantiation life cycle describes the sequence of steps that occur when you create a component object from a component class. As part of that life cycle, Flex automatically calls component methods, dispatches events, and makes the component visible.

The following example creates a Button control and adds it to a container:

<?xml version="1.0"?>

<!--
components\AddButtonToContainer.mxml -->
<
mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

<
mx:Box id="box1" width="200">
<
mx:Button id="button1" label="Submit"/>

</
mx:Box>
</
mx:Application>



The following ActionScript is equivalent to the portion of the MXML code. Flex executes the same sequence of steps in both examples.

// Create a Box container.
var box1:Box = new Box();
// Configure the Box container.
box1.width=200;

// Create a Button control.
var button1:Button = new Button()
// Configure the Button control.
button1.label = "Submit";

// Add the Button control to the Box container.
box1.addChild(button1);


The following steps show what occurs when you execute the ActionScript code to create the Button control, and add it to the Box container. When you create the component in MXML, Flex 2 SDK generates equivalent code.

You call the component's constructor, as the following code shows: // Create a Button control.
var button1:Button = new Button()


You configure the component by setting its properties, as the following code shows:// Configure the button control.
button1.label = "Submit";


You call the addChild() method to add the component to its parent, as the following code shows:// Add the Button control to the Box container.
box1.addChild(button1);


Flex performs the following actions to process this line:

Flex sets the parent property for the component to reference its parent container.
Flex computes the style settings for the component.
Flex dispatches the add event from the button
Flex dispatches the childAdd event from the parent container.
Flex dispatches the preinitialize event on the component. The component is in a very raw state when this event is dispatched. Many components, such as the Button control, create internal child components to implement functionality; for example, the Button control creates an internal UITextField component to represent its label text. When Flex dispatches the preinitialize event, the children, including the internal children, of a component have not yet been created.
Flex creates and initializes the component's children, including the component's internal children.
Flex dispatches the initialize event on the component. At this time, all of the component's children have been initialized, but the component has not been fully processed. In particular, it has not been sized for layout.
Later, to display the application, a render event gets triggered, and Flex does the following.
Flex completes all processing required to display the component, including laying out the component.
Flex makes the component visible by setting the visible property to true.
Flex dispatches the creationComplete event on the component. The component has been sized and processed for layout and all properties are set. This event is dispatched only once when the component is created.
Flex dispatches the updateComplete event on the component. Flex dispatches additional updateComplete events whenever the position, size, or other visual characteristic of the component changes and the component has been updated for display.
You can later remove a component from a container using the removeChild() method. The removed child's parent property is set to null. If you add the removed child to another container, it retains its last known state. If there are no references to the component, it is eventually deleted from memory by the garbage collection mechanism of Adobe Flash Player.

Given this sequence of actions, you should use the events as follows:

The preinitialize event occurs too early in the component life cycle for most initialization activities. It is useful, however, in the rare situations where you must set the properties on a parent before the children are created.
To configure a component before Flex has determined its visual appearance, use the initialize event. For example, use this for setting properties that affect its appearance, height, or width.
Use the creationComplete event for actions that rely on accurate values for the component's size or position when the component is created. If you use this event to perform an action that changes the visual appearance of the component, Flex must recalculate its layout, which adds unnecessary processing overhead to your application.
Use the updateComplete event for actions that must be performed each time a component's characteristics change, not just when the component is created.

Class hierarchy for visual components

Object
|
EventDispatcher
|
DisplayObject
|
InteractiveObject
|
DisplayObjectContainer
|
Sprite
|
UIComponent
|
AllComponent

Event propagation

When events are triggered, there are three phases in which Flex checks whether there are event listeners. These phases occur in the following order:

First, capturing
Next, targeting
Finally, bubbling
During each of these phases, the nodes have a chance to react to the event. For example, assume the user clicks a Button control that is inside a VBox container. During the capturing phase, Flex checks the Application object and the VBox for listeners to handle the event. Flex then triggers the Button's listeners in the target phase. In the bubbling phase, the VBox and then the Application are again given a chance to handle the event now in the reverse order from the order in which they were checked in the capturing phase.

In ActionScript 3.0, you can register event listeners on a target node and on any node along the event flow. Not all events, however, participate in all three phases of the event flow. Some types of events are dispatched directly to the target node and participate in neither the capturing nor the bubbling phases. All events can be captured unless they are dispatched from the top node.

Other events may target objects that are not on the display list, such as events dispatched to an instance of the Socket class. These event objects flow directly to the target node, without participating in the capturing or bubbling phases. You can also cancel an event as it flows through the event model so that even though it was supposed to continue to the other phases, you stopped it from doing so. You can do this only if the cancelable property is set to true.

Capturing and bubbling happen as the Event object moves from node to node in the display list: parent-to-child for capturing and child-to-parent for bubbling. This process has nothing to do with the inheritance hierarchy. Only DisplayObject objects (visual objects such as containers and controls) can have a capturing phase and a bubbling phase in addition to the targeting phase.

Mouse events and keyboard events are among those that bubble. Any event can be captured, but no DisplayObject objects listen during the capturing phase unless you explicitly instruct them to do so. In other words, capturing is disabled by default.

When a faceless event dispatcher, such as a Validator, dispatches an event, there is only a targeting phase, because there is no visual display list for the Event object to capture or bubble through.

Using the introspection API

If you want to list all the public properties and methods of a nondynamic (or sealed) class or class instance, use the describeType() method and parse the results using the E4X API. The describeType() method is in the flash.utils package. The method's only parameter is the target object that you want to introspect. You can pass it any ActionScript value, including all available ActionScript types such as object instances, primitive types such as uint, and class objects. The return value of the describeType() method is an E4X XML object that contains an XML description of the object's type.

The describeType() method returns only public members. The method does not return private members of the caller's superclass or any other class where the caller is not an instance. If you call describeType(this), the method returns information only about nonstatic members of the class. If you call describeType(getDefinitionByName("MyClass")), the method returns information only about the target's static members.

The following example introspects the Button control and prints the details to TextArea controls:

<?xml version="1.0"?>

<!--
usingas/IntrospectionAPI.mxml -->
<
mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="getDetails()">

<
mx:Script><![CDATA[
import
flash.utils.*;

public function
getDetails():void {
// Get the Button control's E4X XML object description.
var classInfo:XML = describeType(button1);

// Dump the entire E4X XML object into ta2.
ta2.text = classInfo.toString();

// List the class name.

ta1.text = "Class " + classInfo.@name.toString() + "\n";

// List the object's variables, their values, and their types.
for each (var v:XML in classInfo..variable) {

ta1.text += "Variable " + v.@name + "=" + button1[v.@name] +
" ("
+ v.@type + ")\n";
}


// List accessors as properties.
for each (var a:XML in classInfo..accessor) {

// Do not get the property value if it is write only.
if (a.@access == 'writeonly') {
ta1.text += "Property " + a.@name + " (" + a.@type +")\n";
}


else
{
ta1.text += "Property " + a.@name + "=" +
button1[a.@name] + " (" + a.@type +")\n";
}
}


// List the object's methods.

for each (var m:XML in classInfo..method) {

ta1.text += "Method " + m.@name + "():" + m.@returnType + "\n";
}
}
]]></
mx:Script>

<
mx:Button label="Submit" id="button1"/>
<
mx:TextArea id="ta1" width="400" height="200"/>

<
mx:TextArea id="ta2" width="400" height="200"/>
</
mx:Application>


The output displays accessors, variables, and methods of the Button control, and appears similar to the following:
Class mx.controls::Button
...
Variable id=button1 (String)
Variable __width=66 (Number)
Variable layoutWidth=66 (Number)
Variable __height=22 (Number)
Variable layoutHeight=22 (Number)
...
Property label=Submit (String)
Property enabled=true (Boolean)
Property numChildren=2 (uint)
Property enabled=true (Boolean)
Property visible=true (Boolean)
Property toolTip=null (String)
...
Method dispatchEvent():Boolean
Method hasEventListener():Boolean
Method layoutContents():void
Method getInheritingStyle():Object
Method getNonInheritingStyle():Object

Another useful method is the ObjectUtil's getClassInfo() method. This method returns an Object with the name and properties of the target object. The following example uses the getClassInfo() and toString() methods to show the properties of the Button control:


<?xml version="1.0"?>

<!--
usingas/IntrospectionObjectUtil.mxml -->
<
mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

<
mx:Script><![CDATA[
import
mx.controls.Alert;

import
mx.utils.ObjectUtil;
private function
showProps(b:Button):void {

var
o:Object = ObjectUtil.getClassInfo(b);
ta1.text = ObjectUtil.toString(o);
}
]]></
mx:Script>

<
mx:Button id="b1" label="Show Properties" click="showProps(b1)"/>

<
mx:TextArea id="ta1" width="300" height="500"/>
</
mx:Application>