Abdulcode

Pages

Aug 18, 2010

AS3 : with keyword

It can be used to write cleaner code when setting multiple properties of the same object.

Normal Code:
var circle:Sprite = new Sprite();
circle.graphics.beginFill(0xFFCC00);
circle.graphics.drawCircle(100,100,50);
circle.graphics.endFill();
addChild(circle);


Using with keyword Code:
var circle:Sprite = new Sprite();
with (circle.graphics)
{
beginFill(0xFFCC00);
drawCircle(100, 100, 50);
endFill();
}
addChild(circle);

Jul 29, 2010

Flex : VideoDisplay

VideoDisplay control to play back video files that have been encoded as either Flash Video (FLV) videos or MPEG-4 videos with H.264 encoding. The VideoDisplay control can display both progressive download video and streaming video. A Flex VideoDisplay control can be created with the <mx:VideoDisplay> MXML tag.

The Flex framework comes with only the most basic video controls, which is the video playback control. It doesn’t include a prebuilt video player with play and pause buttons or a volume control. You can easily build your own, simple playback controls, but just be aware that the VideoDisplay control displays only video.

Code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
horizontalAlign="center"
backgroundGradientAlphas="[1.0, 1.0]"
backgroundGradientColors="[#000000, #000000]">

<mx:Script>
<![CDATA[

import mx.events.VideoEvent;

[Bindable]
private var videoStatus:String;

private function callPlayHead(e:VideoEvent):void
{
videoStatus = videoDispID.playheadTime +
" / " + videoDispID.totalTime;
}
]]>
</mx:Script>

<mx:VideoDisplay id="videoDispID"
source="assets/Video Song.flv"
playheadUpdate="callPlayHead(event);"/>

<mx:Label text="Status : {videoStatus}"
color="#4E92A0"
fontWeight="bold"/>

<mx:HBox>
<mx:Button label="Play"
enabled="{videoDispID.playing == false}"
click="videoDispID.play();"/>
<mx:Button label="Pause"
enabled="{videoDispID.playing == true}"
click="videoDispID.pause();"/>
<mx:Button label="Stop"
enabled="{videoDispID.playing == true}"
click="videoDispID.stop();"/>
</mx:HBox>

</mx:Application>

Jul 26, 2010

Function parameters

Pass by Value
function passPrimitives(xParam:int, yParam:int):void
{
xParam++;
yParam++;
trace(xParam, yParam);
}

var xValue:int = 10;
var yValue:int = 15;

trace(xValue, yValue); // 10 15
passPrimitives(xValue, yValue); // 11 16
trace(xValue, yValue); // 10 15

Pass by Reference
function passByRef(objParam:Object):void
{
objParam.x++;
objParam.y++;
trace(objParam.x, objParam.y);
}

var objVar:Object = {x:10, y:15};

trace(objVar.x, objVar.y); // 10 15
passByRef(objVar); // 11 16
trace(objVar.x, objVar.y); // 11 16
The objParam parameter references the same object as the global objVar variable. As you can see from the trace statements in the example, changes to the x and y properties of the objParam object are reflected in the objVar object.

Jul 23, 2010

AS3 : Dynamic classes

A dynamic class defines an object that can be altered at run time by adding or changing properties and methods. A class that is not dynamic, such as the String class, is a sealed class. You cannot add properties or methods to a sealed class at run time.

You create dynamic classes by using the dynamic attribute when you declare a class. For example, the following code creates a dynamic class named "DynamicClass".

Code : /*Main.as*/
package
{
import flash.display.Sprite;

public class Main extends Sprite
{
public function DynamicClassCode()
{
var dClass:DynamicClass = new DynamicClass();

dClass.age = 25; // Dynamically add new variable.
// Dynamically add new Method.
dClass.getDetails = function():void
{
trace(dClass.nama);
trace(dClass.age);
}

dClass.getDetails(); // Method call
}
}
}

dynamic class DynamicClass
{
public var nama:String = "Abdul";
}

Jul 22, 2010

Flex: Custom Tooltip - IToolTip

While Creating the Tooltip the main thing is, the particular component/control's attribute toolTip=" " must contain space or any char's, but should not be empty or null.

Sample Main: /*Main.mxml*/
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical">

<mx:Script>
<![CDATA[
import com.abdul.TipComp;
import mx.events.ToolTipEvent;

private function callTootTip(e:ToolTipEvent):void
{
var touchedLabel:String = e.target.label;

var tc:TipComp = new TipComp();
tc.setText = touchedLabel; // pass value to the component.

e.toolTip = tc;
}
]]>
</mx:Script>

<mx:Button label="Tool Tip Button"
toolTip=" "
toolTipCreate="callTootTip(event)"/>
</mx:Application>


Here,
1. In the user define component we have to implement the IToolTip interface like this implements="mx.core.IToolTip".
2. The setText (it is a user define method for our convenience) method is used to get the value from the caller.
3. Image is used as a ToolTip.

Sample Component: /*TipComp.mxml*/
<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"
implements="mx.core.IToolTip"
horizontalAlign="center"
verticalAlign="middle">

<mx:Script>
<![CDATA[
import mx.core.IToolTip;

[Bindable]
private var value:String = "";

/* used to get value from the caller */
public function set setText(value:String):void
{
this.value = value;
}

public function set text(txt:String):void
{
}

public function get text():String
{
return "";
}
]]>
</mx:Script>

<mx:Label id="lab"
text="{value}"/>
<mx:Image x="87"
y="10"
height="280"
width="226"
source="@Embed(source='Earth_axis.jpg')"/>
</mx:VBox>

Jul 21, 2010

Number to String Conversion

Syntax:
toString(radix);

radix Specifies the numeric base (from 2 to 36) to use for the number-to-string conversion.
Sample:
package
{
import flash.display.Sprite;

public class Sample_AS extends Sprite
{
public function Sample_AS()
{
var num:int = 241;

trace(num.toString(2)); // Binary
trace(num.toString(8)); // Octal
trace(num.toString(16)); // Hexadecimal
}
}
}

Jul 20, 2010

Actionscript with MySQL

Today I walk thru the Database connectivity. At that time I got some of the interesting thing about the DB connectivity. ie) MySQL with Flex / AS3 / AIR.

By using the SWC and below mentioned sample code, we directly connect the MySQL with AS3.

Download the assql swc file.

Sample
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
initialize="init();">

<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.rpc.AsyncResponder;

import com.maclema.mysql.Connection;
import com.maclema.mysql.MySqlToken;
import com.maclema.mysql.ResultSet;
import com.maclema.mysql.Statement;

private var con:Connection;

public function init():void
{
var SERVER_ADDRESS:String = "localhost";
var PORT:int = 3306;
var DB_USER:String = "root";
var DB_PASS:String = "root";
var DB_NAME:String = "test";

con = new Connection(SERVER_ADDRESS, PORT,
DB_USER, DB_PASS, DB_NAME);
con.addEventListener(Event.CONNECT, handleConnected);
con.connect();
}

private function handleConnected(e:*):void
{
execute();
}

private function execute():void
{
var query:String = "SELECT name FROM Names";
var st:Statement = con.createStatement();
st.sql = query;

var token:MySqlToken = st.executeQuery();
token.mynote = 'abdul';
token.addResponder(new AsyncResponder(result, fault, token));
}

[Bindable]
private var arr:ArrayCollection;

private function result(data:Object, token:Object):void
{
var rs:ResultSet = ResultSet(data);
arr = new ArrayCollection();

while (rs)
{
if (rs.next())
arr.addItem(rs.getString("name"));
else
break;
}
}

private function fault(info:Object, token:Object):void
{
trace("Error: " + info + "Token" + token.mynote);
}
]]>
</mx:Script>

<mx:List dataProvider="{arr}"
width="25%"
height="50%">
</mx:List>

</mx:Application>

Flex: Creating custom events

All MXML components can dispatch events, either those inherited by the components from their superclasses, or new events that you define within your components. When you are developing MXML components, you can add your own event types.

In this example, you define a new component called MyText.mxml that uses a
tag as its root tag. This component also defines a new property called enableTI that users set to true to enable text input or to false to disable input.

The setter method dispatches a new event type, called enableEvent, when the value of the enableTI variable changes. The [Event] metadata tag identifies the event to the MXML compiler so that the file referencing the component can use the new property.

Syntax for the [Event] metadata tag:
 <mx:Metadata>
[Event(name="eventName", type="eventType")]
</mx:Metadata>

Example : /*MyText.mxml*/
<?xml version="1.0" encoding="utf-8"?>
<mx:TextInput xmlns:mx="http://www.adobe.com/2006/mxml">

<mx:Metadata>
[Event(name="enableEvent", type="flash.events.Event")]
</mx:Metadata>

<mx:Script>
<![CDATA[
public function set enableTI(bool:Boolean):void
{
this.enabled=bool;
dispatchEvent(new Event("enableEvent"));
}

public function get enableTI():Boolean
{
return this.enabled;
}
]]>
</mx:Script>

</mx:TextInput>

Example : /*Main.mxml*/
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
xmlns:abdul="com.abdul.*">

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

private function enableEventHandler(e:Event):void
{
Alert.show("Event Handler");
}
]]>
</mx:Script>

<abdul:MyText id="myText"
enableTI="true"
enableEvent="enableEventHandler(event);"/>

<mx:Button click="{myText.enableTI=!myText.enableTI}"/>

</mx:Application>

Jul 17, 2010

Flex : Display Hand Cursor on Components

If you want to display a hand cursor over a Flex component, there are two properties that come handy. useHandCursor and buttonMode. In some cases, a third property called mouseChildren might be required as well.

buttonMode property


Specifies the button mode of this sprite. If true, this sprite behaves as a button, which means that it triggers the display of the hand cursor when the mouse passes over the sprite and can receive a click event if the enter or space keys are pressed when the sprite has focus. You can suppress the display of the hand cursor by setting the useHandCursor property to false, in which case the pointer is displayed.

mouseChildren property

Determines whether or not the children of the object are mouse enabled. If an object is mouse enabled, a user can interact with it by using a mouse. The default is true.

If you look at the code below, there are 4 different controls (Label, Image, Button and Text), all 4 of them will display a handCursor but if you notice, for Label and Text, I had to use mouseChildren = false to achieve this and for Image and Button, simply doing buttonMode = true did the trick.
 <mx:Label buttonMode="true"
text="testing here"
useHandCursor="true"
mouseChildren="false"/>
<mx:Image source="someimage.gif"
buttonMode="true"/>
<mx:Button label="Button"
buttonMode="true"/>
<mx:Text text="testing again"
buttonMode="true"
useHandCursor="true"
mouseChildren="false"/>

I understand what mouseChildren means, if we set it to false, it basically stops all the mouse activities on that control and we need to do custom events for mouse actions but why I had to set it to false for Label and Text, I am not sure yet! Maybe someone can explain ?

My overall conclusion is, if you want to get a hand cursor, use all 3 properties, sounds like the safest bet to me, atleast we know its going to work!

useHandCursor = true
buttonMode = true
mouseChildren = false

Jul 12, 2010

AS3 Snippet: FlexEvent.IDLE

A FlexEvent.IDLE event will dispatch every 100 milliseconds when there has been no keyboard or mouse activity for 1 second.

Code :
this.systemManager.addEventListener(FlexEvent.IDLE, userIdle);
private function userIdle(e:FlexEvent):void {
if(e.currentTarget.mx_internal::idleCounter == 3000){
//do something!
}
}
If the event trigger means, the control pass to the method.
In this method, we check the condition for that the system is idle for 5mins.
(Five minutes is equal to 300000 milliseconds… divided by 100 ticks and
the number we need to check against is 3000).

Flex: ChangeWatcher Class

Today I studied across a handy utility class called ChangeWatcher, which lives inside the mx.binding.utils package. It provides you with a handy way of watching other object’s properties.

Syntax :
ChangeWatcher.watch(object, "property", handler);

Object – the object which owns the property
"property" – the property you want to watch
handler – the function name of the handler
Whenever the property of the object changes, the handler will respond.
The property that ChangeWatcher is watching must be [Bindable] and Public.

Sample :
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
creationComplete="initApp();">
<mx:Script>
<![CDATA[
import mx.binding.utils.ChangeWatcher;
import mx.controls.Alert;
import mx.events.PropertyChangeEvent;

[Bindable]
public var tmpData:String="welcome";

private function initApp():void
{
ChangeWatcher.watch(this, "tmpData", watchHandler);
}

private function watchHandler(e:PropertyChangeEvent):void
{
// Do Something
}

private function clickHandler():void
{
if (tmpData == "welcome")
tmpData=tmpData.toUpperCase();
else
tmpData=tmpData.toLowerCase();
}
]]>
</mx:Script>

<mx:Label text="{tmpData}"/>
<mx:Button click="clickHandler()"/>

</mx:Application>