using Arguments in addEventListener
To pass parameter in addEventListener
addEventListener(MouseEvent.CLICK, function(e:MouseEvent){onClickEvent(e,”Argument”)});
Posts Tagged ‘ using ’
To pass parameter in addEventListener
addEventListener(MouseEvent.CLICK, function(e:MouseEvent){onClickEvent(e,”Argument”)});
The below custom functions might be of use where you don’t want to use currency formatter or numeric Formatter of AS3
public function currencyFormat( number:Number ):String {
var words:Array = String( number ).split( “” ).reverse();
var results:Array = new Array();
var l:int = words.length;
for ( var i:int = 0; i < l; i++ ) {
results.push( words[i] );
if ( i % 3 == 2 ) {
results.push( “,” );
}
}
return results.reverse().join( “” );
}public function prefixZero( number:Number, figure:int ):String {
var str:String = String( number );
for ( var i:int = 0; i < figure; i++ ) {
str = “0″ + str;
}
return str.substr( str.length – figure, str.length );
}
The Below code demonstrates the conversion of ByteArray to BitmapData. In the below case, SWF is loaded and converted into BitmapData
private function swfLoad_complete(evt:Event):void {
byteArrayToBitmapData(swf.content.loaderInfo.bytes);
}
private function byteArrayToBitmapData(ba:ByteArray):void {
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, getBitmapData);
loader.loadBytes(ba);
}
private function getBitmapData(e:Event):void {
var content:* = loader.content;
var BMPData:BitmapData = new BitmapData(content.width,content.height);
var UIMatrix:Matrix = new Matrix();
BMPData.draw(content, UIMatrix);
}
The code below demonstrates the data type conversions among basic DataTypes used most in Flex. The ‘init()’ method does to and from conversion for ArrayCollection to XML and XML to ArrayCollection
Object, String, XML, ArrayCollection
import mx.collections.ArrayCollection;
import mx.rpc.xml.SimpleXMLEncoder;
import mx.rpc.xml.SimpleXMLDecoder;
import mx.utils.ObjectUtil;
private function xmlToArrayCollection(xml:XML):ArrayCollection{
var xmlDoc:XMLDocument = new XMLDocument(xml.toString());
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);
var ac:ArrayCollection =new ArrayCollection(Array(resultObj.root.list.source.item));
return ac;
}
private function objectToXML(obj:Object):XML {
var qName:QName = new QName(“root”);
var xmlDocument:XMLDocument = new XMLDocument();
var simpleXMLEncoder:SimpleXMLEncoder = new SimpleXMLEncoder(xmlDocument);
var xmlNode:XMLNode = simpleXMLEncoder.encodeValue(obj, qName, xmlDocument);
var xml:XML = new XML(xmlDocument.toString());
return xml;
}
private function objectToArrayCollection(obj:Object):ArrayCollection {
var ac:ArrayCollection = new ArrayCollection(obj as Array);
return ac;
}
private function arrayCollectionToXML(ac:ArrayCollection):XML{
var xml:XML = objectToXML(ac);
return xml;
}
private function init():void{
var arr:Array = new Array();
arr.push({data:0,name:’deva’});
arr.push({data:1,name:’raj’});
var ac:ArrayCollection = new ArrayCollection(arr);
var xml:XML = arrayCollectionToXML(ac);
var newAc:ArrayCollection = xmlToArrayCollection(xml);
trace(newAc[0][0].name);
}
private function objToStr(value:Object,indent:int =0,
refs:Dictionary= null,
namespaceURIs:Array = null,
exclude:Array = null):String{
var str:String;
var refCount:int = 0;
if (value is Date)
{
return value.toString();
}
else if (value is XMLNode)
{
return value.toString();
}
else if (value is Class)
{
return “(” + getQualifiedClassName(value) + “)”;
}
else
{
var classInfo:Object = ObjectUtil.getClassInfo(value, exclude,
{ includeReadOnly: true, uris: namespaceURIs });
var properties:Array = classInfo.properties;
str = “(” + classInfo.name + “)”;
if (refs == null)
refs = new Dictionary(true);
var id:Object = refs[value];
if (id != null)
{
str += “#” + int(id);
return str;
}
if (value != null)
{
str += “#” + refCount.toString();
refs[value] = refCount;
refCount++;
}
var isArray:Boolean = value is Array;
var isDict:Boolean = value is Dictionary;
var prop:*;
indent += 2;
for (var j:int = 0; j < properties.length; j++)
{
str = newline(str, indent);
prop = properties[j];
if (isArray)
str += “[";
else if (isDict)
str += "{";
if (isDict)
{
str += objToStr(prop, indent, refs,
namespaceURIs, exclude);
}
else
{
str += prop.toString();
}
if (isArray)
str += "] “;
else if (isDict)
str += “} = “;
else
str += ” = “;
try
{
str += objToStr(value[prop], indent, refs,
namespaceURIs, exclude);
}
catch(e:Error)
{
str += “?”;
}
}
indent -= 2;
return str;
}
}
private static function newline(str:String, n:int = 0):String
{
var result:String = str;
result += “\n”;
for (var i:int = 0; i < n; i++)
{
result += ” “;
}
return result;
}
/* General function for Conversion (thanks, Krystian Bień)
public function xmlToArrayCollection(xml:XML):ArrayCollection{
var temp:String = ‘<items>’ + xml.toString() + ‘</items>’;
xml = XML(temp);
var xmlDoc:XMLDocument = new XMLDocument(xml.toString());
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);
var ac:ArrayCollection;
ac = new ArrayCollection();
ac.addItem(resultObj.items);
return ac;
}*/
I came across the efflex.org. Its so amazing.. someone took effort to make such library.. I compiled a zip with required Lib elements on this link efflex.
Some Basic String functions:
public function replaceChars(str:String, Char:String, replace:String) : String
{
var result:String = “”;
for (var i:int = 0; i < str.length; i++) {
if (str.charAt(i) == Char)
{
result += replace;
}
else
{
result += str.charAt(i)
}
}
return result;
}public function trimWhiteSpace(str:String) : String
{
var pattern:RegExp = /[\s]+/g;
return str.replace(pattern, “”);
}public function containsAlphaNumeric(str:String) : Boolean
{
var pattern:RegExp = /[^a-zA-Z0-9]/;
return str.search(pattern) != 0;
}
I have came through the thread and this is my solution to protect the product with a serial key uncrackable.
The solution can be used in both Online browser based / AIR products.
The MD5 class does create a Unique system ID and verifies the MD5 checksum with a foreign key to check whether the user is registered or not.
MD5.registereduser – Boolean returns true, if user is registered.
MD5.skey - The Serial key to be used, to register (can store in a db or xml)
MD5.setRegKey(MD5.skey); – To unlock the product.
Loading Image from local file system using the power of Flash Player 10, Filereference.load()
Check the Demo the link contains the source file.
Like Chemical CoValent Bonding, Bind two Objects of Flex through this
AS3 Utility…
package
{
import flash.events.Event;
import mx.binding.utils.ChangeWatcher;
public class CovalentBindig
{
public static function Bond(obj1:Object, prop1:String, obj2:Object, prop2:String):void
{
var flag:Boolean = false;
ChangeWatcher.watch(obj1, prop1, function(event:Event):void
{
if(!flag)
{
flag = true;
obj2[prop2] = obj1[prop1];
flag = false;
}
});ChangeWatcher.watch(obj2, prop2, function(event:Event):void
{
if(!flag)
{
flag = true;
obj1[prop1] = obj2[prop2];
flag = false;
}
});
}
}
}
Dotted Line, Utility Class for AS3
package {
import flash.display.Graphics;
import flash.geom.Point;
public class DotLine{
public function DotLine( target:Graphics, seg:Number=20, xx:Number=0, yy:Number=0 ):void{
this.target = target;
this.now = new Point( xx, yy );
this.seg = seg;
this.rest = 0;
this.flag = false;
}
public var target : Graphics;
public var seg : Number;
public var now : Point;
public var rest : Number;
public var flag : Boolean;
public function dotLineTo( xx:Number, yy:Number ):void{
var s: Point = new Point( now.x, now.y );
var e: Point = new Point( xx, yy );
var d:Number = Point.distance( s, e );
now.x = e.x;
now.y = e.y;
rest = (seg * 1 < rest) ? rest – seg * Math.floor( rest / seg ) : rest;
if(d <= rest){
rest -= d;
if(flag){
target.lineTo( e.x, e.y );
flag = (rest == 0) ? false : true;
}
else{
target.moveTo( e.x, e.y );
flag = (rest == 0) ? true : false;
}
return void;
}var m:Number = 1 / ( d / seg );
var n:Number = 1 / ( d / rest );for( var i:Number=1-n; 0<i; i-=m ){
var a: Point = Point.interpolate( s, e, i );
if(flag){
target.lineTo( a.x, a.y );
flag = false;
}
else{
target.moveTo( a.x, a.y );
flag = true;
}
if( i – m < 0 ){
var b: Point = Point.interpolate( s, e, i – m );
var c: Point = Point.interpolate( s, e, 0 );
rest = Point.distance( e, b );
if(flag){
target.lineTo( c.x, c.y );
}
else{
target.moveTo( c.x, c.y );
}
}
}
}}
}
Collision Detection Utility class for AS3,
Usage: var collide:Rectangle = checkForCollision(obj1, obj2);
package {
import flash.display.BitmapData;
import flash.display.BlendMode;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.geom.Matrix;
import flash.geom.ColorTransform;
import flash.geom.Rectangle;public class CollisionDetection{
public static function checkForCollision(firstObj: DisplayObject,secondObj: DisplayObject):Rectangle
{
var bounds1:Object = firstObj.getBounds(firstObj.root);
var bounds2:Object = secondObj.getBounds(secondObj.root);if (((bounds1.right < bounds2.left) || (bounds2.right < bounds1.left)) || ((bounds1.bottom < bounds2.top) || (bounds2.bottom < bounds1.top)) ) {
return null;
}var bounds:Object = {};
bounds.left = Math.max(bounds1.left,bounds2.left);
bounds.right= Math.min(bounds1.right,bounds2.right);
bounds.top = Math.max(bounds1.top,bounds2.top);
bounds.bottom = Math.min(bounds1.bottom,bounds2.bottom);var w:Number = bounds.right-bounds.left;
var h:Number = bounds.bottom-bounds.top;if(w < 1 || h < 1)
{
return null;
}var bitmapData:BitmapData = new BitmapData(w,h,false);
var matrix:Matrix = firstObj.transform.concatenatedMatrix;
matrix.tx -= bounds.left;
matrix.ty -= bounds.top;
bitmapData.draw(firstObj,matrix,new ColorTransform(1,1,1,1,255,-255,-255,255));matrix = secondObj.transform.concatenatedMatrix;
matrix.tx -= bounds.left;
matrix.ty -= bounds.top;
bitmapData.draw(secondObj,matrix,new ColorTransform(1,1,1,1,255,255,255,255),BlendMode.DIFFERENCE);var intersection:Rectangle = bitmapData.getColorBoundsRect(0xFFFFFFFF,0xFF00FFFF);
/*try{
bitmapData.dispose();
}catch(e:Error){}*/if (intersection.width == 0) { return null; }
intersection.x += bounds.left;
intersection.y += bounds.top;return intersection;
}
}
}
The AS3 Utility Class to add commands in a queue, the usage and class is below:
/**
* var commands : CommandsQueue = new CommandsQueue();
* commands.addCommand( this, myFunc );
* commands.addCommand( this, myFunc2, [0,2], this, Event.COMPLETE );
* commands.execute();
*/
package
{
import flash.events.Event;
import flash.events.EventDispatcher;public class CommandsQueue extends EventDispatcher
{
protected var commands : Array;
protected var _index : Number = 0;
public var onComplete : Function;public function CommandsQueue():void
{
commands = [];
}
public function addCommand( thisObj : Object, func : Function, params: Array = null , completeEventDispatcher : Object = null, completeEventName : String= null ) : void
{
commands.push({
thisObj : thisObj,
func : func,
completeEventDispatcher : completeEventDispatcher || thisObj,
completeEventName : completeEventName,
params : params
})
}
public function get progress():Number
{
return (commands.length>0)? _index / commands.length * 100 : 0;
}
public function cancel() : void
{
throw new Error(“commandQueue.cancel is not implemented yet”);
}
public function execute() : void
{
doNext();
}
public function get index():int
{
return _index;
}
public function get length():int
{
return commands.length;
}
protected function doNext() : void
{
var act : Object = commands[ _index ];if( act.completeEventName ){
act.completeEventDispatcher.addEventListener(act.completeEventName, _commandComplete, false, 0, true);
act.func.apply( act.thisObj, act.params );
} else {
act.func.apply( act.thisObj, act.params );
doNextCommand();
}
}
protected function doNextCommand() : void
{
var act : Object = commands[ _index ];if( act.completeEventName )
act.completeEventDispatcher.removeEventListener(act.completeEventName, _commandComplete);_index ++;
if( _index == commands.length )
{
commands = []; //remove all registerd command for GC
if( onComplete != null )
onComplete();
dispatchEvent( new Event(Event.COMPLETE) );
}else{
doNext();
}
}
protected function _commandComplete( e : Event ) : void
{
doNextCommand();
}
}
}
The below class serves as Garbage Collection utility for AS3. You can use it to prevent your applications from memory leakage.
package{
import flash.events.TimerEvent;
import flash.system.System;
import flash.utils.Timer;
public class GCUtil {
private var _timer:Timer;
public function GCUtil(interval_sec:uint = 60) {
_timer = new Timer(interval_sec*1000);
startGC(interval_sec);
}
public static function doGC():void {
System.gc();
}
public function startGC(interval_sec:uint):void {
if (interval_sec > 0) {
_timer.delay = interval_sec*1000;
if (!_timer.running) {
_timer.addEventListener(TimerEvent.TIMER, handleTimer);
_timer.start();
}
} else {
stopGC();
}
}
public function stopGC():void {
if (!_timer.running) {
_timer.removeEventListener(TimerEvent.TIMER, handleTimer);
_timer.stop();
_timer.delay = 0;
}
}
private function handleTimer(te:TimerEvent):void {
doGC();
}
}
}
I am glad to announce the first Step for basic requirements of E-Learning using Flex has been achieved.
Basic Requirements met:
See the demo of loading a number of animations. The source files include floader.mxml, ForcibleLoader.as and XML
The below function validates the email ID string using regular expression.
private function validateEmail(mailid:String):Boolean {
var emailExpression:RegExp = /^[a-z][\w.-]+@\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
return emailExpression.test(mailid);
}//e-mail option 2:
/[a-zA-Z0-9!$&*.=^`|~#%'+\/?_{}-]+@([\w_-]+\.)+[a-zA-Z]{2,4}/;
//URL:
/(https?|ftp|svn)(:\/\/[\w-_.:;!?~*\'()\/\@&=+\$,%#]+)/;
//Color:
/#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})/;
//String Quote:
/(“|’)(.+)?\1/;
IP evaluation:
var ipPattern:RegExp = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/;
| M | T | W | T | F | S | S |
|---|---|---|---|---|---|---|
| « Mar | ||||||
| 1 | 2 | 3 | 4 | 5 | ||
| 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 | 17 | 18 | 19 |
| 20 | 21 | 22 | 23 | 24 | 25 | 26 |
| 27 | 28 | 29 | 30 | 31 | ||