Add

AS3 + Useful Little Things…


Here is a little list of useful tidbits and pieces of information I have discovered or encountered. Some are simple and obvious, and some are just nice to have handy.

If you come across any more, let us all know!

How to determine the number of times a substring shows up in a string. In this example we want to know how many times "http://" exists in a string:

var s:String = "http:// hdfkajsdhfksdh kj akjdhf ksjdh http:// jsdf asdlkfj  http:// http://";
var pattern:RegExp = /http:\/\/+/g;
var results:Array = s.match(pattern);
trace(results.length); // 4

How to address the main swf preloader issue in IE7:

this.addEventListener("enterFrame",onEnterFrame);
 
function onEnterFrame(e:Event) {
    loadbar.width = (this.loaderInfo.bytesLoaded/this.loaderInfo.bytesTotal)*200;
    if (this.loaderInfo.bytesLoaded == this.loaderInfo.bytesTotal) {
        gotoAndPlay(2);
        this.removeEventListener("enterFrame", onEnterFrame);
    }
}

External javascript call that doesn't bother you:

var playerType:String = Capabilities.playerType;
if (playerType == "External" || playerType == "StandAlone") {
    //
} else {
    navigateToURL(new URLRequest("javascript:setHeight(200);"), '_self');
}

Phone and Email validation using REGEX:

// REGEX for email validation
function validateEmail(email:String):Boolean {
	var emailExpression:RegExp = /^[a-z][\w.-]+@\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
	return ! emailExpression.test(email);
}
// REGEX for phone validation
function validatePhone(phone:String):Boolean {
	var emailExpression:RegExp = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/i;
	return ! emailExpression.test(phone);
}

Calling another function with arguments using Tweener:

Tweener.addTween(
	item, {
		alpha: 0,
		time:.3,
		transition:"easeoutquad",
		onComplete:anotherFunction, //Completed Event Callback
		onCompleteParams:[arg1, arg2, arg3] //anotherFunction(arg1:String, arg2:String, arg3:String)
	}
);

Simple button interaction:

submitBT.addEventListener(MouseEvent.MOUSE_OVER, submitInteraction);
submitBT.addEventListener(MouseEvent.MOUSE_OUT, submitInteraction);
submitBT.addEventListener(MouseEvent.CLICK, submitInteraction);
 
function submitInteraction(event:MouseEvent):void {
	switch (event.type) {
		case MouseEvent.MOUSE_OVER :
			Tweener.addTween(event.currentTarget, {alpha: 1, time:.2, transition:"easeoutquad"});
			return;
		case MouseEvent.MOUSE_OUT :
			Tweener.addTween(event.currentTarget, {alpha: .7, time:.2, transition:"easeoutquad"});
			return;
		case MouseEvent.CLICK :
			submitForm();
			return;
	}
}

ADDED_TO_STAGE

pv3dContainer.addEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
 
function handleAddedToStage(event:Event):void {
	trace(event);
}

I would suggest avoiding this at all costs. use a setTimeout() function if you need a delay otherwise find another way to call the event. My nightmare with this was confirmed during the Papervision 2.0 seminar when we removed it.

Consistency is the key to effective troubleshooting. That being said here are a couple things that throw that off as well as useful tips:

  • Small images will still load across domains. When security should prevent cross domain loading. (I get the feeling the security is dependent on the file size?)
  • Assets will instantiate in some browsers and some won't in IE7. (Make sure you hit the frame with assets when preloading. Obvious practice, but when you see thing instantiate when you don't, makes it easy to overlook)
  • Remember that the edit multiple frames button in the timeline is your friend. (It's next to the right of the new layer button under the keyframe area in the timeline)
  • Actionscript video cue points are not precise. Cuepoints embedded in the FLV are.
  • Check out the gradient transform tool. It's a hidden gem.
  • Flash has an easier time rendering filters when the values are exponents of 2, so if you can do x/y blur value pairs using 2, 4, 8, 16, 32. you might see a performance increase with multiples of 2 as well.

The Discussion

see what everyone is saying

  • Some Cool AS3 Tips… May 2nd, 2008 at 8:52 pm #1

    [...] Hyrdotik has a great post with some very useful AS3 tips: Click here [...]

  • HaunGo June 19th, 2008 at 10:43 am #2

    Hi, can someone elaborate on this bullet point:

    " Assets will instantiate in some browsers and some won’t in IE7. (Make sure you hit the frame with assets when preloading. Obvious practice, but when you see thing instantiate when you don’t, makes it easy to overlook) "

    I think it relates to a problem I'm having. When I refresh the browser (not on the initial load), parts of my swf are missing. It only happens in IE.

    I've never seen anything like it.

    -Thanks

  • djdonovan June 19th, 2008 at 11:17 am #3

    Sorry I should have worded that better. Basically you need to make sure that your preloaders frames are in fact hitting frames that have your library assets placed on them, I was experiencing a strange thing where the loop wasn't hitting the frames with the assets on them. One would assume this wouldn't work as the assets aren't being instantiated. However in Safari, the assets would load fine which can add an extra layer for debugging if you aren't looking out for it. Hope that helps!

Respond

get in on the action.

* Required

bottega veneta deep coffee pocket bag deep weight loss pills bingo and game casino gambling online virtual how to win at slots versace deep coffee venus bag women does viagra work online bingo uk discount drugstore where to get viagra or cialis diazepam cheap without rx bingo and slots does cialis really work bingo gaming chanel yellow shoulder bag bingo for cash slot machine buy meds online without presciption lancel pearl premier flirt prada white shoulder bag prescriptions pain killers without a prescription viagra product information cialis generic levitra viagra cialis male enhancement online gambling offers manolo blahnik beige hangisi valium indications anya hindmarch beige hobo how does diazepam work who has the cheapest cialis price for tramadol levitra website price for generic viagra top anti depressants pharmacy zolpidem marc jacobs antique gold keylock messenger bag pill for acne casino gambling buy carisoprodol cheap create poker website zyban tablet jimmy choo purple wells shoes valtrex medication counseling for erectile dysfunction hey bingo louis vuitton patent beige sandals louis vuitton monogram idylle pink tote power bingo slot games gucci black evening bag xanax fedex oral jelly viagra new casino slots discount erectile dysfunction medication christian louboutin white ambrosina pumps poker machine games buy no phentermine prescription high stakes poker buy tory burch golden reva ballerina flats casino locations roulette casinos play online casinos bingo and slots viagra effect on women louis vuitton damier graphite keepall bandouliere marc jacobs royal blue keylock shoulder bag play roulette online casino mania online buy compazine buy gucci black trainers online casinos en internet how to win slots christian louboutin blush barcelona sandals prescription diet drugs us only mobile casino games natural clomid buy overseas viagra online casino canada online xanax fedex norvasc generic erectile dysfunction products zoloft canada uk viagra supplier casino bonus tory burch deep blue tory logo rain boots poker for money prescription drugs online adipex no prescription needed pharmacies geniune cialis no prescription ambien dosing how do muscle relaxants work valentino beige snakeskin clutch what is tadalafil ativan dosages sales viagra ysl white muse bag cialis to buy online gambling strategy cheapest phentermine pills christian dior biege medium saddle handbag alprazolam brand cheap viagra new zealand low cost adipex bally patent patent red jana tote ambien pharmacy manolo blahnik bow booties what is viagra used for dosage viagra new diet pill fda approved play slots online now cialis best price las vegas bingo cialis generic tabs versace purple venita bow satchel chloe patent purple cyndi tote fendi apricot snake peekaboo handbag discount lipitor prescription ambien ambien 10mg poker us levitra free samples do meridia phentermine work the same order celine black shoulder bag louis vuitton patent black sandals over the counter medication cheap 37 5 phentermine safe effective diet pills loewe white handbag dolce gabbana black trainers buying phentermine alprazolam generic for xanax ativan 2mg prada beige fairy l bag generic cialis canadian diet phentermine viagra online cheap europe cialis platinum play bingo levitra info prescription drugs migraines levitra alternative phentermine ingredient how does cialis work louis vuitton damier azure canvas galliera gm order amoxicillin new arthritis and psoriasis drug lipitor online pharmacy professional blackjack how does cialis ultram ingredients