ActionScript 3: Serializing Classes using registerClassAlias

In previous article “Component and SharedObject Example” we’ve seen how to store simple variables in Local Shared Object. But, what if you want to store a custom class objects in Shared Object?

You can use flash.net. registerClassAlias() to do so. This method is similar to old Object.registerClass() (Removed in AS3).

Shared Objects are stored in AMF (Action Message Format) format. When you try to save class object in Shared Object, it will be stored as normal object. It will not have any reference to the class. Thus to save the information about the class, one has to use registerClassAlias class. This is also called as Serializing Classes.

Apart from SharedObject, this class can be used for LocalConnection, ByteArray , NetConnection and NetStream.

Here is a simple example of using registerClassAlias. In this example, object of Person class is stored in Shared Object. This example also demonstrates use of AS3 components (Label, ComboBox, Button, InputText).

AS3 Serializing example image

Below is the code:

Class Person:

package {
public class Person {
private var _name:String;
private var _age:uint;
private var _gender:String;
public function Person() {
this._name = "";
this._age = undefined;
this._gender = "";
}
public function get name():String {
return this._name;
}
public function set name(name:String):void {
this._name = name;
}
public function get age():uint {
return this._age;
}
public function set age(age:uint):void {
this._age = age;
}
public function get gender():String {
return this._gender;
}
public function set gender(gender:String):void {
this._gender = gender;
}
public function getPerson():String {
return "Name: " + this._name + " Age: " + this._age + " Gender: " + this._gender;
}
}
}

Class soExample:

package {
import fl.controls.Button;
import fl.controls.Label;
import fl.controls.TextInput;
import fl.controls.NumericStepper;
import fl.controls.ComboBox;
import fl.data.DataProvider;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.net.SharedObject;
import flash.net.registerClassAlias;
public class soExample extends Sprite {
private var getData_btn:Button;
private var setData_btn:Button;
private var delData_btn:Button;
private var titleLbl:Label;
private var statLbl:Label;
private var nameLbl:Label;
private var ageLbl:Label;
private var genderLbl:Label;
private var name_txt:TextInput;
private var ageNS:NumericStepper;
private var genderCB:ComboBox;
private var _mc:Sprite;
private var mySO:SharedObject;
private var tushar:Person;
public function soExample(_mc:Sprite) {
registerClassAlias(”PersonAlias”, Person);
this._mc = _mc;
updateUI();
updateDisplay();
getSO();
}
private function updateUI():void {
getData_btn = createButton("Get Shared Object", 150, 10, 160, "get_btn");
setData_btn = createButton("Store Shared Object", 150, 10, 190, "set_btn");
delData_btn = createButton("Delete Shared Object", 150, 10, 220, "del_btn");
titleLbl = createLabel("<b>AS3 - Shared Object Example</b>", 200, 10, 10);
statLbl = createLabel("", 400, 10, 250);
nameLbl = createLabel("Name: ", 100, 10, 50);
ageLbl = createLabel("Age: ", 100, 10, 80);
genderLbl = createLabel("Gender: ", 100, 10, 110);
name_txt = createTextInput(200, 60, 50);
ageNS = createNumericStepper(25, 50, 22, 60, 80);
genderCB = createComboBox(100, 22, 60, 110, new DataProvider(["Male", "Female"]));
}
private function updateDisplay():void {
_mc.addChild(titleLbl);
_mc.addChild(nameLbl);
_mc.addChild(ageLbl);
_mc.addChild(genderLbl);
_mc.addChild(statLbl);
_mc.addChild(getData_btn);
_mc.addChild(setData_btn);
_mc.addChild(delData_btn);
_mc.addChild(ageNS);
_mc.addChild(name_txt);
_mc.addChild(genderCB);
}
private function createButton(lbl:String, w:uint, x:uint, y:uint, nme:String):Button {
var BTN:Button = new Button();
BTN.label = lbl;
BTN.width = w;
BTN.move(x, y);
BTN.name = nme;
BTN.addEventListener(MouseEvent.CLICK, clickHandler);
return BTN;
}
private function createLabel(lbl:String, w:uint, x:uint, y:uint):Label {
var LBL:Label = new Label();
LBL.htmlText = lbl;
LBL.width = w;
LBL.move(x, y);
return LBL;
}
private function createTextInput(w:uint, x:uint, y:uint):TextInput {
var TI:TextInput = new TextInput();
TI.htmlText = "";
TI.width = w;
TI.move(x, y);
return TI;
}
private function createNumericStepper(defaultVal:uint, w:uint, h:uint, x:uint, y:uint):NumericStepper {
var NS:NumericStepper = new NumericStepper();
NS.move(x, y);
NS.setSize(w, h);
NS.minimum = 1;
NS.maximum = 150;
NS.stepSize = 1;
NS.value = defaultVal;
return NS;
}
private function createComboBox(w:uint, h:uint, x:uint, y:uint, _data:DataProvider):ComboBox {
var CB:ComboBox = new ComboBox();
CB.move(x, y);
CB.setSize(w, h);
CB.dataProvider = _data;
return CB;
}
private function clickHandler(event:MouseEvent):void {
respondToMouseEvent(event.target.name);
}
private function respondToMouseEvent(nme:String):void {
switch (nme) {
case "get_btn":
getSO();
break;
case "set_btn":
setSO();
break;
case "del_btn":
deleteSO();
break;
}
}
private function getSO():void {
name_txt.text = "";
mySO = SharedObject.getLocal(”person”);
if (mySO.size == 0) {
// Shared object doesn’t exist.
statLbl.htmlText = "Status: SharedObject not found.";
name_txt.text = "";
ageNS.value = 25;
genderCB.selectedIndex = 0;
} else {
name_txt.text = mySO.data.person.name;
ageNS.value = mySO.data.person.age;
if(mySO.data.person.gender == "Female"){
genderCB.selectedIndex = 1;
}
statLbl.htmlText = "Status: SharedObject value is - <b>"+mySO.data.person.getPerson()+"</b>";
}
}
private function setSO():void {
if (name_txt.text != "") {
tushar = createPerson(name_txt.text, ageNS.value, genderCB.selectedItem.data);
mySO.data.person = tushar;
mySO.flush();
getSO();
} else {
statLbl.htmlText = "Status: <b>Name</b> missing.";
}
}
private function deleteSO():void {
mySO.clear();
getSO();
}
private function createPerson(name:String, age:uint, gender:String):Person {
var tmpPerson = new Person();
tmpPerson.name = name;
tmpPerson.age = age;
tmpPerson.gender = gender;
return tmpPerson;
}
}
}

Now, create object of soExample and pass movieclip reference (in which all the components will be added at runtime) as parameter:

var mySoExample:soExample = new soExample(this);

Note: Be sure to add “Button”, “Label”, “ComboBox”, “NumericStepper” & “TextInput” components to the library of that movie.

Source:  AS3 Serializing Example (Zip file included)

Posted in ActionScript3, AS3, components, Flash | 25 Comments

Action Script 3: Component and SharedObject Example

Here is a simple tutorial on using prebuilt AS3 components and SharedObject.

SharedObject Example

Class soExample:

package {
import fl.controls.Button;
import fl.controls.Label;
import fl.controls.TextInput;

import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.net.SharedObject;

public class soExample extends Sprite {
private var getData_btn:Button;
private var setData_btn:Button;
private var delData_btn:Button;
private var titleLbl:Label;
private var statLbl:Label;
private var soText:TextInput;
private var _mc:Sprite;
private var mySO:SharedObject;

public function soExample(_mc:Sprite) {
this._mc = _mc;
updateUI();
updateDisplay();
getSO();
}
private function updateUI():void {
getData_btn = createButton(getData_btn, "Get Shared Object", 150, 10, 100, "get_btn");
setData_btn = createButton(getData_btn, "Store Shared Object", 150, 10, 130, "set_btn");
delData_btn = createButton(getData_btn, "Delete Shared Object", 150, 10, 160, "del_btn");
titleLbl = createLabel(titleLbl, "<b>AS3 - Shared Object Example</b>", 200, 10, 10);
statLbl = createLabel(statLbl, "", 400, 10, 200);
soText = createTextInput(soText, 200, 10, 50);
}
private function updateDisplay():void {
_mc.addChild(titleLbl);
_mc.addChild(soText);
_mc.addChild(getData_btn);
_mc.addChild(setData_btn);
_mc.addChild(delData_btn);
_mc.addChild(statLbl);
}
private function createButton(btn:Button, lbl:String, w:uint, x:uint, y:uint, nme:String):Button {
btn = new Button();
btn.label = lbl;
btn.width = w;
btn.move(x, y);
btn.name = nme;
btn.addEventListener(MouseEvent.CLICK, clickHandler);
return btn;
}
private function createLabel(lblRef:Label, lbl:String, w:uint, x:uint, y:uint):Label {
lblRef = new Label();
lblRef.htmlText = lbl;
lblRef.width = w;
lblRef.move(x, y);
return lblRef;
}
private function createTextInput(tiRef:TextInput, w:uint, x:uint, y:uint):TextInput {
tiRef = new TextInput();
tiRef.htmlText = “”;
tiRef.width = w;
tiRef.move(x, y);
return tiRef;
}
private function clickHandler(event:MouseEvent):void {
respondToMouseEvent(event.target.name);
}
private function respondToMouseEvent(nme:String):void {
switch (nme) {
case "get_btn":
getSO();
break;
case "set_btn":
setSO();
break;
case "del_btn":
deleteSO();
break;
}
}
private function getSO():void {
soText.text = "";
mySO = SharedObject.getLocal("userData");
if (mySO.size == 0) {
// Shared object doesn’t exist.
statLbl.htmlText = "Status: SharedObject not found.";
} else {
statLbl.htmlText = "Status: SharedObject value is - <b>"+mySO.data.userName+"</b>";
}
}
private function setSO():void {
if (soText.text != "") {
mySO.data.userName = soText.text;
mySO.flush();
}
getSO();
}
private function deleteSO():void {
mySO.clear();
getSO();
}
}
}

Now, create object of soExample and pass movieclip reference (in which all the components will be added at runtime) as parameter:

var mySoExample:soExample = new soExample(this);

Note: Be sure to add “Button”, “Label” & “TextInput” components to the library of that movie.

Publish and test the flash file. Simple isn’t it 🙂

Posted in ActionScript3, AS3, Flash | 15 Comments

Action Script 3: Resize SWF on Browser resize

 

Accessing Stage object was pretty simple in previous versions of Action Script. However, it’s little different in Action Script 3. Sprits (movie clip) have property named stage (notice small “s”). One can use this property to access the Stage Object and respond to the Stage object’s Resize event.

Here is the AS3 code to resize SWF depending on browser size:

Class myStage:

package {

import flash.display.Stage;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;

public class myStage extends Sprite {

private var _mc:Sprite;
private var mcStage:Stage;

public function myStage(_mc:Sprite){
this._mc = _mc;
mcStage = _mc.stage;
addStageListener();
}

public function addStageListener() {
mcStage.scaleMode = StageScaleMode.NO_SCALE;
mcStage.align = StageAlign.TOP_LEFT;
mcStage.addEventListener(Event.RESIZE, resizeHandler);
}

private function resizeHandler(event:Event):void {
trace("stageWidth: "+mcStage.stageWidth);
trace("stageHeight: "+mcStage.stageHeight);
_mc.x = mcStage.stageWidth/2;
_mc.y = mcStage.stageHeight/2;
}
}
}

Now, create object of myStage and pass movieclip reference (which you want to align at center of stage) as parameter:

var mystage:myStage = new myStage(_mc);

Publish the flash file. Be sure to put 100% as value for Height and Width parameters in Object and param tag in HTML.

All set! Now you can test your file. SWF should now respond as you resize the browser window.

Posted in ActionScript3, Flash | 28 Comments

Free ActionScript 3 Videos

Just a quick post. If you are looking for some free Flash ActionScript 3 videos, check out Wikivid.

Direct link for the AS 3 videos: http://wikivid.com/index.php/Flash#Actionscript_3.0

Posted in ActionScript3, Flash | 4 Comments

Affinitiz is Awesome!

Today, while browsing through the Flex.org site, I came to know about Affinitiz’s blog publishing application. After trying this out, I can say that this is simply one of the best application done in Flex.

You can view all sort’s of statistics of your blog, can publish over a dozen type of content including, Video, Poll files etc.

Good application!

Btw: Check out my blog on Affinitiz – http://www.affinitiz.com/space/tushar/blog 

Posted in Uncategorized | 4 Comments

What a Sunday!

These days, we are enjoying awesome climate here at Pune. Rainy season is on!

Here is the picture I took when rain was stopped for about an hour.

Sunday Evening

Nice, rainy, cool, pleasant Sunday evening…

Posted in Misc | 2 Comments

Flash, Savour of the Mobile Universe?

Nice article!

Check out Mobile Marketing Magazine’s view on why Flash is one of the important player in Mobile Devices when it comes to rich mobile experience. Here is the link. Good news for Flash Lite Developers 🙂

Posted in Flash Lite | Leave a comment

Want to create Poll? try Tezaa!

Tezaa

If you want to create your own poll, go to Tezaa. It’s simple, fast & free!
Tezaa is an online community that is driven by polls. Any member can create, modify and participate in a poll.

iTWire has posted an article on Tezaa, check it out here.

More Info: About Tezaa, Tezaa Blog

So, who is the man behind Tezza?
As usual, my good friend Shalin has come up with a brilliant idea!

I’ve created my own poll, do post your votes 🙂

Do you like Tezaa?

Posted in Misc | 1 Comment

Hidden Button Tool

While playing with JSFL, I developed this tool. This tool is useful to create Invisible Buttons (Button with only Hit Area) in Flash.

This MXP includes Hidden Button Tool & Hidden Button Command.

Hidden Button Tool can be used to create rectangular hidden button. For creating hidden buttons of custom shapes, use Hidden Button Command.

Hidden Button Tool has parameter of “Show Hand Cursor”, if it is set to false; the “useHandCursor” property of that particular button will be false.

All the buttons created using this tool/command will be available in “Hidden Buttons” folder in Library.

After installing the MXP file, you will have to customize & add “Hidden Button Tool” your tools panel (Edit > Customize Tools Panel).

Tips, Suggestions, Bugs, Improvements are invited
(send them to tusharwadekar@gmail.com).

Download Hidden Button Tool

Disclaimer Notice: Use at your own risk 🙂

Posted in JSFL | Leave a comment

JSFL: library.itemExists Bug?

library.itemExists method fails to understand the character (upper/lower case) difference.

As per the documentation, this method returns “true” if the specified item exists in the library & “false” otherwise.

Create a folder named “MovieClips” in the Library & try following code:
fl.getDocumentDOM().library.itemExists(“movieclips”);
Notice that all characters are same. Only difference is the string is in small case.

It returns false! & if you try to create folder using following code, it silently fails.
fl.getDocumentDOM().library.newFolder(“movieclips”);

However if you manually try to create folder using Library Panel, you will get an error message “The name “movieclips” is already taken. Please use a different name.

Here is the JSFL code I am using:
// JSFL Script
var doc;
var folderName = “MovieClips”
// Initialization
function init() {
fl.outputPanel.clear();
doc = fl.getDocumentDOM();
if (doc != null) {
var lib = doc.library;
if(!lib.itemExists(folderName)){
lib.newFolder(folderName);
fl.trace(‘Success. ‘+folderName+’ created.’);
} else {
fl.trace(‘Error. ‘+folderName+’ already exists.’);
}
} else {
fl.trace(‘Error. You must open a FLA file first.’);
}
}
init();
// End Script

Any comments?

Posted in JSFL | 1 Comment