Archive for the ‘ActionScript 3’ Category

dataprovider for datagrid

June 19, 2008

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”vertical” viewSourceURL=”../src/Layout02.mxml”>
<mx:Script>
<![CDATA[
private function myLabelFunc(item:Object, dataField:DataGridColumn):String
{
var p:String = item.Price? item.Price: "N/A";
return item.Year+" / " +p;
}
]]>
</mx:Script>
<mx:ArrayCollection id=”dgPD”>
<mx:source>
<mx:Object Artist1=”Pavement” Album1=”Slanted and Enchanted” Price1=”11.99″ Year=”2003″/>
<mx:Object Artist=”Finches” Album=”Daniel’s Song” Price2=”11.99″ Year=”2007″/>
<mx:Object Artist=”Pavarotti” Album=”Twilight” Price=”11.99″ Year=”1999″/>
<mx:Object Artist=”Other” Album=”Other” Price=”5.99″ Year=”2002″/>
</mx:source>
</mx:ArrayCollection>

<mx:VBox>
<mx:Label text=”Data matter!”/>
<mx:DataGrid id=”myDG” width=”400″ rowCount=”10″ dataProvider=”{dgPD}”>
<mx:columns>
<mx:DataGridColumn headerText=”ARTIST” dataField=”Artist”/>
<mx:DataGridColumn headerText=”ALBUM” dataField=”Album”/>
<mx:DataGridColumn headerText=”YEAR &amp; PRICE” labelFunction=”myLabelFunc”/>
<!–<mx:DataGridColumn headerText=”PRICE” dataField=”Price”/>–>
</mx:columns>
</mx:DataGrid>
</mx:VBox>

</mx:Application>

Use swc in flex

May 5, 2008

Scenario 1: You need to compile ActionScript code as a reusable component in Flex Builder.

Solutions: Follow the steps (FB plugin v3):

Step 1. Compile swc. First you will need to create a new “Flex Library Project”. Then copy all the actionscript code into the top folder of your project file, retaining the package/namespace structure (fig. 1)

The file structure and xml manifest file in Flex Library Project

In “src” folder, you would need a xml-manifest.xml file where you declare the class and id (optional, default to the class name anyways) (fig 1). Thirdly, you would need to define your namespace for the class that’s going to be referenced in MXML (or Flash?) like so: In the AS class fine, inside the class definition, just like the way as you declare a variable, add “public namespace fc;” (substitue “fc” with whatever your choice of namespace). If you’ve enabled “build automatically” (under “Project” menu command), FB will instantaneously build the deploy files for you the time you save the AS file. The result is the complied .swc file, which you can find in the “bin” folder in your library project.

Step 2. Use swc in your Flex project. You either need to copy the swc file(s) into the library-path folders as defined in your flex-config.xml, or explicitly tell Flex to use the swc you want in your current project. To do so, go to “Project properties”->”Flex Build Path”->”Library Path”->”Add SWC”. You can simply navigate to the swc file in the Flex library project as defined in Step 1. After Flex compiled the project, you can use the component as defined in your ActionScript code. Here is an extract:

<mx:HBox>
<mx:Label text=”Search by last name: “/>
<fc:AutoComplete id=”lastNameSrchAC” dataProvider=”{listInfo}” labelField=”lastName”/>
</mx:HBox>

See also: Namespaces in Flex and Soprano

scroll datagrid by actionscript (flex 3)

April 30, 2008

//Highlight the itemrender
dgPeopleList.selectedIndex = 212;

//validateNow needs to be called before verticalScrollPosition is set.
dgPeopleList.validateNow();

dgPeopleList.verticalScrollPosition = 212;

Mouse hitTest (collision test) in AS 2

April 6, 2008

As a spatially challenged person (easily lost in a street/inside an office building/mall, etc.), I am always confused by the maths that is required when converting a spatial point from one coordinate space into another (localToGlobal, globalTolocal, etc. in Flash).

But hitTest for mouse cursor (collision test to see if mouse cursor collide with movieclip/subclass instances) is much more straightforward ;) You always test the mouse coordinates at the _root; this also holds true when you load the swf as an external file using MovieClip.loadMovie or MovieClipLoader.loadClip.

var bigMC:MovieClip;
var cir:MovieClip = bigMC.cir;
var rec:MovieClip = bigMC.rec;


var lsnr:Object = new Object();
lsnr.onMouseMove = function(evt:Object)
{
var tof:Boolean = cir.hitTest(_root._xmouse, _root._ymouse, true);
if(tof)trace(tof);
}
Mouse.addListener(lsnr);

In actionScript 3, the cumbersome way of using onMouseMove is gone because of the added event types such as MOUSE_OVER and MOUSE_OUT.

Stop event propagation

March 5, 2008

I was coding a small control. When it’s clicked, it unfolds itself and starts to respond to user input; when the user clicks anywhere after this, it folds back and stops responding to user input.

Basically there are two sources for the click event: the object itself and the Stage. Based on which state the object is in, it behaves differently. Here is what the mouse click handler looks like:

if(_state==FOLDED)
{
unfold();
stepper["registerSource"](stage);
removeEventListener(MouseEvent.CLICK, handleClick);
stage.addEventListener(MouseEvent.CLICK, handleClick);
}else if(_state==UNFOLDED)
{
fold();
stepper["unregisterSource"](stage);
stage.removeEventListener(MouseEvent.CLICK, handleClick); addEventListener(MouseEvent.CLICK, handleClick);
_state = (_state == FOLDED)? UNFOLDED: FOLDED;

The control didn’t seem to change its state with just this code. The reason is that once one source is removed from the event listeners list, another one is added to the list. Since the click event continues to bubble through, and the two sources are executing the same code (as shown above), so the switch between states seems to ultimately cancel each other.

Solution:

To make it work, just add one line on top of the code, like this:

evt.stopImmediatePropagation();

This eventually makes the state transfer smooth.

Full-screen mode in Flash 8

February 19, 2008

How to create true fullscreen movies with Flash

Exploring full-screen mode in Flash Player 9

Quick facts:

  1. Only supported with Flash Player 9.0.28  or above;
  2. Can be implemented in Flash 8 IDE by modifying the Stage class;
  3. Can only be initiated with  user inputs such as mouse click or keypres;
  4. An overlay dialog box will appear when the movie enters full-screen mode, instructing the user how to exit and return to normal mode.

E4X in ActionScript 3 and Flex 3

January 1, 2008

The following top AS3 classes, in conjunction with HTTPService and mx.rpc.events.ResultEvent classes are used in Flex (2+) to handle XML:

XML/XMLList/Namespace/QName

XMLList Class can be considered a collection of XML objects. It is a native ActionScript class that is advised to handle XML such as data binding. XMLNode has become the legacy class in AS 2.

So the first step of handling XML data is to deserialize an XML document or object into XMLList objects.

<mx:HTTPService id="dataFetcher" url="http://mysite/myData.xml" resultFormat="e4x" result="onData(event)" />

Remember you will almost always need to initialize the call by adding the following code to the “creationComplete” event handler of the mx:Application node:

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” creationComplete=”dataFetcher.send()”/>

To deserialize the an XML object (sample shown as follows), use ResultEvent Class, like so:

<delSum Test="1" timestamp="2007-12-10T21:07:48Z">
<del pId=”Dem” dNeed=”2029″ dTot=”4056″ dChosen=”991″ dToBeChosen=”3237″>
<Cand cId=”1746″ cName=”Clinton” dTot=”290″ d1=”+290″ d7=”+290″ d30=”+150″/>
<Cand cId=”1918″ cName=”Obama” dTot=”194″ d1=”+194″ d7=”+194″ d30=”+55″/>
</del>
<del pId=”GOP” dNeed=”1113″ dTot=”2225″ dChosen=”251″ dToBeChosen=”2153″>
<Cand cId=”893″ cName=”Romney” dTot=”109″ d1=”+109″ d7=”+109″ d30=”+1″/>
<Cand cId=”302″ cName=”Paul” dTot=”47″ d1=”+47″ d7=”+47″ d30=”0″/>
</del>
</delSum>

private function onData(event:ResultEvent):void
{
demData = event.result.del.(@pId==”Dem”).Cand.(@cName!=”Uncommitted”);
gopData = event.result.del.(@pId==”GOP”).Cand.(@cName!=”Uncommitted”);
}

Note that event.result represents the top node, which is <delSum> node in the XML document.

XML filtering:

To locate a set of XML objects that represents similar characteristics, use the parenthesis () to include sets of boolean statements, following a dot after the node you want to carry out the filtering against, like so:

var product1:XMLList = catalog.product.(@id==1);//Returning the product node or nodes if there are multiple products whose id is equal to 1

or

var productName:String = catalog.product.(price<50).name;//Returns the name node

or

var manufName:String = catalog.product.(price<50).@manufacturer;//Returns the manufacturer attribute under the name node

To get list of candidate names:

var _tst:XMLList = event.result.del.(@pId=="GOP").Cand.(@cName!="Uncommitted").@cName
trace((_tst[0] is XML)+”; “+_tst[0].nodeKind() )//Returns “true; attribute”
trace(gopData[0].@cName+”; “+(gopData[0].nodeKind())//Returns “Romney; element”

Types of node include: text, comment, processing-instruction, attribute, or element.

Timeline, MovieClip and AS 3 101

October 8, 2007

1. A MovieClip subclass instance starts playing as soon as it’s been instantiated:


var myMC:MyMC = new MyMC();

AddChild(myMC); or removeChild(myMC) doesn’t affect the playhead in myMC, meaning if there is no framescript, myMC will continue playing regardless of whether it’s been added to the playlist or not.

2. To use the versatile/artistic/rétrospectif/timeline-script style, one thing to keep in mind is if any children MovieClip symbols are physically placed inside the timeline of your MovieClip subclass, you can either have Flash make those variable declarations automatically (and thus you should not declaring them as variables in your timeline script), or associate your movieClip symbol with an external class file definition and remove those variable declaration in the class. (in such a case, you will still have Flash declare those children instances variables for you but you will have to make them public in your class.)

Link: Flash CS3: Automatic Timeline Declarations

3. To use an external class definition for a MovieClip symbol and associate timeline script with it, use addFrameScript(frameObj1, frameHandler1, frameObj2, frameHandler2, *rest);. Note that frameObject is zero based: meaning if you want to use frame number, frame one would need a value of 0.

4. To determine if a displayObject is on the playlist or not, check to see if either of the following revolves to true or false:

displayObject.stage

displayObjectParentsOrAncestor.contains(displayObject)

5. Since the timeline script is synchronized by “Event.ENTER_FRAME“, it might be it’s delayed because of other script took longer to execute. As an animator, I found myself, especially in my earlier days of using Flash, put a stop() on some frame (say that frame is labeled “paused”) of a MC symbol and in my client code, I need to gotoAndPlay("paused") to resume from that specific point. It would sometimes get confusing since gotoAndPlay("paused") won’t always resume the playhead, instead it seems to freeze at that certain frame; that is because the frame script stop() is executed AFTER gotoAndPlay("paused") is executed . A quick-n-dirty workaround is to simply do the following:

gotoAndStop("paused");
gotoAndPlay(currentFrame+1);

or

gotoAndPlay(pausedFrameNumber+1);

6. Render Event

7. Flash 9: Timeline navigation and code execution

useHandCursor, buttonMode and mouseChildren

October 7, 2007

To display the hand cursor for a displayObject with a dynamic textfield inside it (Suppose the textfield is on top of a shape):

mySprite.buttonMode = true;
//By default useHandCursor is true;
//mySprite.useHandCursor = true;
mySprite.mouseChildren = false;

Internal, protected, public, private 101

September 23, 2007

Public, internal, protected methods should be marked “override” in a derived class when be ovverriden. Also the visibility and signature of these methods cannot be changed by the derived class.

Static and private methods are hiding from the outside world.
So a derived class is unaware of its parent class’ static/private members, which means you can create static or private methods with the same name but different signatures in the derived class than the static/private methods in its parent classes.

Static methods are treated differently than non-static ones.
A static method can co-exist with an instance method with the same name. The signature can also be different.

Example:

package test
{
import flash.display.Sprite;

public class InheritanceTest01 extends Sprite
{
public function InheritanceTest01()
{
var a1:A1 = new A1();
//a1.sayHi(”we should go beers”, “have fun”);
//a1.walk(12);
A1.sayHi();
}
}
}

class A
{
private function sayHi():void
{
trace(”hi!”);
}

protected function walk(distance:Number):void
{
trace(”I will walk for “+distance+” miles.”);
}

public function run():void
{
trace(”I run!”);
}

internal function sleep(duration:Number):void
{
trace(”I am going to sleep for “+duration+” hours.”);
}
}
class A1 extends A
{
public function A1()
{
super();
sayHi(7);
}
/*
public function sayHi(w1:String, w2:String):void
{
trace(”Oh hi! I am just saying “+w1+” and probably “+w2+”.”);
walk(12);
run();
sleep(1.5);
}
*/
private function sayHi(times: uint):void
{
if(!times)return;
for(var i:uint =0 ; i<times; i++)
{
trace(”hi”);
}
}
static function sayHi():void
{
trace(”Ciao!”);
}

override protected function walk(distance:Number):void
{
trace(”I will walk for “+distance/2+” miles and then another “+distance/2+” miles.”);
}

override public function run():void
{
super.walk(1);
trace(” then “);
super.run();
}

override internal function sleep(duration:Number):void
{
super.sleep(duration);
trace(”and I am going to sleep for another “+duration+” hours!”);
}
}