Flash IDE / AS3 [object global] Inside of Dynamic Function

I ran across an odd situation inside the Flash IDE where I was trying to trace out parameters about the timeline’s class.

Here’s the code I was running:

import flash.events.*
this.addEventListener(Event.ENTER_FRAME, function(e:Event){trace(this)});

the result looked something like this:

[object global]
[object global]
[object global]

This is a result of the dynamically created function created in the event listener. The function is created in some alternate universe called “global” and has nothing to do with the scope of the stage onto which it is placed. The correct code should be:

import flash.events.*
this.addEventListener(Event.ENTER_FRAME, handleFrame);
function handleFrame(e:Event):void
{
	trace(this);
}

This will produce something like:

[object MyClass]
[object MyClass]
[object MyClass]

Coding for Understandability

Often I have a number of options in how to code a particular piece of functionality. I’m constantly balancing between brevity, simplicity, speed, size, and readability. I often find that if I put a little more focus on simplicity and readability, I save myself time and headaches, in addition to making my code more readable, more object oriented, and more accessible to other coders.

I’m going to provide some examples in ECMAScript, but I know that similar problems exist in other languages, as well.

I recently ran across some code that was coded for brevity:

var userdefined:Object = (_model.partner || {}).userdefined || {},
bsb:BannerShownBeacon = new BannerShownBeacon(
	userdefined.dims 
		? userdefined.dims
		: userdefined.width && userdefined.height
			? userdefined.width + 'x' + userdefined.height
			: 'fixed_bottom'
)
;

Now, this is fully valid, well-written code, and it’s also tabbed and line-broken for readability, but what exactly is it doing? What is the purpose of this code?

The difficulty I find is that when someone is trying to determine whether their particular implementation is going to be executed — lets say we have dims, width, and height in our userdefined param, and we’re looking at this the first time. Since coding standards aren’t set for how to structure ? : style if statements, it’s difficult to go through this by instinct and take a guess at what it’s doing. Every language has if/else statements and most coders are intimately familiar with them.

First, we look to see if _model.partner exists and if it doesn’t, we create it, then we check to see if _model.partner.userdefined exists and if not, we create it and assign that to a variable.
Then, we create a second variable called bsb that expects a BannerShownBeacon;
If userdefined has a dims param, we use it, otherwise, we check if it has width and height params, and if it does, we combine them with an x in between, otherwise, we just use the term “fixed_bottom” and make a BannerShownBeacon out of that.

The final option is to include large amounts of comments (which is excellent for non-compiled languages like JS), but in compiled languages, this often doesn’t save any time or lines of code.

I’ve rewritten this here using if/else statements

var bsbText:String = "fixed_bottom";
if(_model.hasOwnProperty("partner"))
{
	if(_model.partner.hasOwnProperty("userdefined"))
	{
		var userdefined:Object = _model.partner.userdefined;
		if(userdefined.hasOwnProperty("dims"))
		{
			bsbText = userdefined.dims;
		}
		else if(userdefined.hasOwnProperty("width") && userdefined.hasOwnProperty("height"))
		{
			bsbText = userdefined.width + "x" + userdefined.height;
		}
	}
}
var bsb:BannerShownBeacon = new BannerShownBeacon(bsbText);

Why use Math.random? Use a Date instead

I’ve always wondered about this. Cache busting is a common need in my field, and I always see people doing something like the following:

Math.floor( Math.random() * 1000000 );

this will produce something like 809959 and *should* be different every time. If all you’re looking for is a unique number, why not use the Unix timestamp? When it comes to cache busting, if the same user is able to reload the same asset twice in the same millisecond, I say they deserve to get weird results.
That said, it’s not technically random, and it’s possible for your code to produce recurrences in the same millisecond, so use it wisely.
Javascript:

new Date().getTime()

Actionscript:

new Date().time()

PHP:

microtime();

Preloading SWF in Firefox using SWFobject doesn’t support overflow = null

I was using the following code to pre-load my SWFs so I could instantiate them later.

swfDiv.style.width = '1px';
swfDiv.style.height = '1px';
swfDiv.style.overflow = 'hidden';
swfDiv.style.position='fixed';
swfDiv.style.top = '0px';
swfDiv.style.left = '0px';

And then, when I wanted to show my SWF, I would call

swfDiv.width = '100%';
swfDiv.height = '100%';
swfDiv.zIndex = 1000;
swfDiv.overflow = null;

This works great in Chrome, but in Firefox, things go really bad and REALLY strange things start happening. Turns out that Firefox doesn’t like null as an overflow attribute.
Setting this to “” instead works fine.

swfDiv.width = '100%';
swfDiv.height = '100%';
swfDiv.zIndex = 1000;
swfDiv.overflow = "";

Cannot Trace using Debugger on OSX

Oh good lord, all I wanted to do was trace the output of my flash debug player, yet there was nothing in the usual location. Typically I just run

tail -f ~/Library/Preferences/Macromedia/Flash\ Player/Logs/flashlog.txt

in the Terminal and it spits out everything Flash does. The file didn’t exist on my system, so I couldn’t tail it. The solution turned out to be a missing mm.cfg file.
in ~/Library/Application\ Support/, produce a mm.cfg file with the following content:

TraceOutputFileEnable=1
ErrorReportingEnable=1

This, along with a correct debugger, should produce traces.

Flash-Injected Javascript does not Minify Properly in Ant

We’re using Flash to inject javascript onto our page, and to save space, we’re using a minifier to produce smaller javascript code. The issue is that we’re using a string replacement on our code and the minifier produces an odd result.

Consider the following code:

var id = myobj['ID_PLACEHOLDER'];

When we inject the code, we do a replace on ID_PLACEHOLDER and replace it with the appropriate ID. This is great, except that our minifier sees this as a waste of chars and minifies the system to:

var id = myobj.ID_PLACEHOLDER;

This would be well and good except that our IDs can begin with numbers and Javascript variables cannot. To solve this, I had to modify our placeholder to be:

var id = myobj['1_ID_PLACEHOLDER'];

This does not minify and produces correct code on the injected end.

ExternalInterface Callbacks not Firing in Firefox when Using SWFObject

Your externalinterface call works fine in chrome, safari, maybe even IE. That’s because it takes a second for Firefox to get with the program and actually shove your object into the element.

here’s a happy little hack to make things work again:
Flash:

import flash.external.ExternalInterface;
ExternalInterface.addCallback("myFunction", myFunction);
function myFunction():void
{
	trace("JS Callback Successful");
}

Javascript:

//the swf id is the object into which SWFobject has loaded your SWF file
var swf= document.getElementById("my_swf_id");
try {
	swf.myFunction();
}
catch (e) { 
	//swf is not loaded yet, wait a bit and try again
	setTimeout(function(){
		swf.myFunction();
	}, 10);
}

ExternalInterface in AS3

Just spent a minute looking for how ExternalInterface works. Here’s some handy code of how to make specific things happen in AS3:

ExternalInterface.call("alert","message");

Launches an alert window with “message” as the content.

trace(ExternalInterface.call("function(){return window.location.href;}"));

The call returns the window.location.href of the current page and is then traced to the output.

Measuring PHP Page Load Time

Note: This is for PHP 5.0 and higher.
I’ve seen a bunch of these out there, but I don’t see why they should be so complex. Here’s the code for the top of your page
$start_time = microtime(true);

Then, at the bottom, put this:
$load_time = microtime(true) - $start_time;

Microtime produces a number that can be used to measure milliseconds. by including true, we request a number instead of a string like “ms sec”, which isn’t what we want.

The $load_time var contains a float (number) that indicates how long the page took to load. Use this as you see fit.

Yancy’s Law of Optimal Delay

A computer science professor at Cal Poly, San Luis Obispo, came up with a law that for any given task, there is a point between procrastination and quality that provides the optimal result.
For example:
You are given an assignment that is due 2 months from now that requires 1 week of work.

Example 1, the early bird:
You begin immediately, you will finish the task with at most 8 weeks to spare.
Unfortunately, your professor then cancels the assignment 3 weeks in and you find that you’ve wasted a week of your time for nothing.

Example 2, the procrastinator:
You wait till 4 days before deadline to begin.
Your quality suffers and you get a bad grade.

Example 3, the optimal delay:
You wait 6 weeks before beginning and take extra time to do a good job.
Your teacher probably won’t cancel their plans last minute, so you’re safe.
You get a good grade and you’re sure you didn’t waste your time.

This applies well to classes, but also applies very well, I’ve found, to the real-world example of my job. I often have tasks that get re-prioritized, canceled, or changed, and this law helps me ensure I’m always on task with something worthwhile.