ES6 Logo!

I’m inspired again! It’s been a while since I have posted anything, so let’s get right into it.

ES6 is here, and there’s no denying it. It is a great improvement to the JavaScript language and vendor support is growing daily.

This is my take on the ES6 Logo. It’s a lot like the HTML 5 Logo and the CSS 3 Logo in that it resembles a shield with the angular letters up top and the version number in sticks. The yellow color was inspired by the popular JSConf logo, but mine has web-safe colors. :)

The E is two Ls inverted with the middle line simply extruded out. The S is a backwards Z. The 6 took some time, and thinking… It is the original 5 with the bottom connected full circle and the top clipped at the handle.

Behold! ES6 is among us!

ES6 LOGO SVG

Posted in ES6 | 2 Comments

HTML 5 & CSS 3 Logos

The irony of this piece is that I used Flash to create the vector art and to export the SVG. GothUltra is the font used in the HTML5 logo, but the letters “CSS” were very curvy and not as angular so I created the C out of two L’s and the S by flipping two capital Z’s. The 3 was a copy of the 5 but I essentially flipped the top portion of the 5 and extruded the middle line to the edge of the lower.


HTML5 CSS3 Logos in SVG

Posted in HTML5 | 55 Comments

Dictionary Class in AS3

When was the last time you used the Dictionary? No, seriously, when was the last time???

[as3]
var dictionary:Dictionary = new Dictionary();
[/as3]

Perhaps one of the most interesting additions to the ActionScript 3 language is the new Dictionary Object. It provides a quick and absolute mechanism for looking up values based on object keys. Much to the same way Array elements are associated by numeric indexes and Objects by string key names, Dictionary elements are associated by the instance of an object.

Associative Lists

[as3]
// Arrays use numeric indexes
var array:Array = new Array();
array[0] = “value”;

// Objects use string indexes
var object:Object = new Object();
object[“key”] = “value”;
//Same as…
object.key = “value”;

// Dictionary uses object keys
var dictionary:Dictionary = new Dictionary();
dictionary[object] = “value”;
[/as3]

Non-Primitive Identifiers

The real beauty of the Dictionary object lies in its effortless and dynamic way of referencing non-primitive objects or custom classes, absolutely. By absolutely, I mean it uses the object’s identity or instance to match up the object, it uses the strict equality (===) for comparison.

[as3]
var dictionary:Dictionary = new Dictionary();
var button:SimpleButton = new SimpleButton();
dictionary[button] = “BUTTON”;

trace(dictionary[button] == “BUTTON”);
//Outputs true because dictionary[button] === “BUTTON”
[/as3]

Primitive Identifiers

On the other hand, primitive or built-in objects, like Numbers, Strings… in a Dictionary collection will act the same way as they would say in an Array [], or a generic Object {} as primitives don’t have new instances and their property or value is returned.

[as3]
//String example
var dictionary:Dictionary = new Dictionary();
dictionary[“a”] = “b”;
trace(dictionary[“a”]); //Outputs “b” because “a”===”b”

//Number example
dictionary[123] = 456;
trace(dictionary[123]); //Outputs 456 because 123===456
[/as3]

It’s also worth noting that the Dictionary object matches based on the instance of the object, not the reference of the object. So, this opens up the possibility for multiple references to the same object with the same key.

[as3]
var a:Object = new Object();
var b:Object = a;
var dictionary:Dictionary = new Dictionary();
dictionary[a] = “abc”;
trace(dictionary[b]); //Outputs ‘abc’ because a===b
[/as3]

Weak Keys

Another feature that sets the Dictionary object apart from an Array or Vector is its ability to hold weak references to its collection. By passing a true to the first and only parameter of the Dictionary object, it will release the object to the garbage collector, of course when all references have been cleared for that object. If you were using an Array or Vector, you would also need to remove the reference from the list whereas the Dictionary will remove it from the collection automatically…

[as3]
var dictionary:Dictionary = new Dictionary(true);
var a:Sprite = new Sprite();

dictionary[a] = new Object();
trace(dictionary[a]); //Outputs [object Object]

a = null; //Clear reference to the Sprite.

trace(dictionary[a]); //Outputs undefined
[/as3]

There are a whole host of applications for the Dictionary Class. I have found it most useful keeping track of form UI elements, namely buttons. It comes in very handy when writing form validation systems or even MouseEvent.CLICK listening for many buttons on a single form. The code below illustrates a scenario where you might have many buttons on a page and instead of having separate event handlers for each instance, you can listen to a container and catch the events on the bubble phase.

Example Application

[as3]
//consts of directions
const TOP:String = “TOP”;
const RIGHT:String = “RIGHT”;
const BOTTOM:String = “BOTTOM”;
const LEFT:String = “LEFT”;

//simply clickable entities
var buttonTop:SimpleButton = randomButton();
var buttonRight:SimpleButton = randomButton();
var buttonBottom:SimpleButton = randomButton();
var buttonLeft:SimpleButton = randomButton();

//movable entity
var ball:Shape = new Shape();

//dictionary key/value pairs
var buttons:Dictionary = new Dictionary();
initButton(buttonTop, TOP);
initButton(buttonRight, RIGHT);
initButton(buttonBottom, BOTTOM);
initButton(buttonLeft, LEFT);

function initView():void
{
var buttonsClip:Sprite = new Sprite();
var ball:Shape = randomBall();
addChild(buttonsClip);
addChild(ball);
for (var button:* in buttons)
{
button.x = buttonsClip.numChildren*(button.width+5);
buttonsClip.addChild(button);
}
//listening to the container clip instead of each individual instance
buttonsClip.addEventListener(MouseEvent.CLICK, onButtonClick, true);
}

function randomBall():Shape
{
with (ball)
{
graphics.beginFill(randomNumber() * 0xFFFFFF);
graphics.drawCircle(0, 0, randomNumber() * 25);
graphics.endFill();
}
ball.x = randomNumber() * stage.stageWidth;
ball.y = randomNumber() * stage.stageHeight;

return ball;
}

function randomButton():SimpleButton
{
return new SimpleButton(buttonState(), buttonState(), buttonState(), buttonState());
}

function buttonState():Sprite
{
var state:Sprite = new Sprite();
with (state)
{
graphics.beginFill(randomNumber() * 0xFFFFFF);
graphics.drawRect(0, 0, 33, 22);
graphics.endFill();
}
return state;
}

function initButton(button:SimpleButton, direction:String):void
{
//dynamically creating the collection
buttons[button] = direction;
}

function onButtonClick(event:MouseEvent):void
{
if (event.target is SimpleButton)
moveObject(buttons[event.target]);
}

function moveObject(direction:String):void
{
trace(“moveObject: ” + direction);

var amount:uint = 5;

switch (direction)
{
case TOP:
ball.y -= amount;
break;
case RIGHT:
ball.x += amount;
break;
case BOTTOM:
ball.y += amount;
break;
case LEFT:
ball.x -= amount;
break;
}
}

function randomNumber():Number
{
return Math.random();
}

initView();
[/as3]

Posted in Flash AS3, Syntax | Tagged , , , , , , | 2 Comments

Try it, if you dare!

Today, I’m going to talk about the Try…Catch…Finally trio. As developers, we perform all the initial testing on our apps before passing them along to the QA team, or even going live with it, depending on your setup. Even with all these eyes looking at your app, there are still unexpected exceptions that can throw the proverbial monkey wrench in your gears. Catching errors is a process that requires code to be executed and examined before it can actually run.  Your app would need to perform, or “try”, the task before actually executing it, and if no errors are found, it will then go ahead and run it.

TCFBlocks

[as3]
try
{
//try block
}
catch(error:ErrorType)
{
//catch block
}
finally
{
//finally block
}
[/as3]

The ActionScript Virtual Machine

More and more apps are consuming and aggregating feeds from various web-services and can come across all sorts of unexpected results. There are two version of the AVM2, the Release Version and the Debugger Version, and any AS3 code running in the Debugger Version of the AVM2 will generate an error message if any such exceptions are met. The reason why I bring this up is because many people are running the Debugger Version without even knowing it, perhaps it was installed by their IT team at work or they installed it unknowingly from the Adobe site. Either way, users will see these pesky errors, and it’s not good to say the least.

Flash Error

Sample Flash Error Screenshot

Back in AS2, the AVM1 would simply fail silently without halting your application. This was obviously pleasing from a users standpoint as they had no idea that something had gone wrong. The same was true from a developers standpoint which made it very difficult to find the problem. By no means am I advocating writing bad or loose code, but simply suppressing errors should be your last resort. As a developer we should test all “possible” scenarios before going live with the app. This is where unit testing comes into play, but we’ll talk more about that when the time comes.

Asynchronous Errors

When publishing a new SWF the compiler will indicate all the syntax errors, if any, but it’s when we start loading data or media from external sources – asynchronously – is where these potential run-time errors lie.  And for this reason, we need to try/test the code before and after actually running it. This will not only suppress the error, but handle it accordingly or perform another necessary task or function. A perfect example of this is loading either an image or a feed from an offline server, or the feed URL has changed, or the feed is empty for whatever reason, unfortunately this happens all the time. The code below will attempt to load a file which doesn’t exist and will be caught in an IOError exception case.

[as3]
var loader:URLLoader = new URLLoader();
loader.addEventListener(IOErrorEvent.IO_ERROR, onDataLoadError);

loader.load(new URLRequest(“noFile.xxx”));

function onDataLoadError(error:IOErrorEvent):void
{
loader.removeEventListener(IOErrorEvent.IO_ERROR, onDataLoadError);
trace(error.text);
//Outputs: Error #2035: URL Not Found.
}
[/as3]

Notice that the try catch is nowhere to be found in this example, we could have enclosed one around the loader.load line, but I don’t like that method, I prefer trying on data in hand. In this case, we add an event listener to the loader instance, if we weren’t listening for loader errors, the user would get a nasty error dialog like the one above.

Say we’ve loaded everything just fine and now we want to cast and manipulate the loaded data, but the XML feed happens to be malformed. Sorry to say, but this is also common. A number of things can cause malformed XML, ie. bad XSL, namespace updates, or an unterminated node.

[as3]
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onDataLoaded);

loader.load(new URLRequest(“http://testng.org/testng-1.0.dtd”));

function onDataLoaded(event:Event):void
{
loader.removeEventListener(Event.COMPLETE, onDataLoaded);

try
{
var xml:XML = new XML(event.target.data);
}
catch (error:TypeError)
{
trace(error.message);
//Outputs: Error #1090: XML parser failure: element is malformed.
}
}
[/as3]

The idea here is to enclose suspicious or error-prone code in the try block, to then respond to that error accordingly using the catch block(s). The finally block will contain code which will execute regardless of the outcome, I and just about everybody I know don’t use the finally block just for that reason indicated. Even if you have a return statement to exit the function, the finally block will still run, very useless if you ask me.

Your try block must be followed by either a catch block, a finally block, or both. You can have as many catch blocks as you want, each variable in the catch case must be typed with the appropriate error type and your try blocks can be nested as deep as they have to go. You can also throw a new error which can be caught using the appropriate catch block, this is of course generating an error on your part, and you might ask yourself, “why are we creating errors, isn’t it our job to prevent them”? Well, the short answer is yes, but if an error isn’t caught using the catch block we can generate it to obey the flow of our error trapping mechanism. When using this method, we would need to throw the error as an instance of the Error class or a subclass there of.

Throw Example

[as3]
function checkEmail(email:String):void
{
if (email.indexOf(“@”) == -1)
{
throw new Error(“Invalid Email Address”);
}
}

try
{
checkEmail(“bobbyberberyan.gmail.com”);
}
catch (error:TypeError)
{
trace(error.message);
//Outputs: Invalid Email Address
}
[/as3]

Posted in Flash AS3, Syntax | Tagged , , , , , , , | Comments Off on Try it, if you dare!

AS3 undefined vs null

Believe it or not, there’s a difference between undefined and null. It may seem redundant to have two constants that represent invalid values/variables, but given the dynamic nature of the ActionScript language, their existence is pretty evident. If you don’t believe me, try the code below.

[as3]
trace(null == undefined); //Outputs true
trace(null === undefined); //Outputs false
[/as3]

ActionScript along with JavaScript are weakly typed languages, though ActionScript 3 is stricter than JavaScript and all of its predicesors, it’s still weak/loose/duck typed. ActionScript 3 is like that crazy cousin we all have that never played by the rules and Flashed everyone off! OK, all pun aside, the * type – or the “untyped” type – can cast anything as anything, which is why ActionScript 3 is still not as strict as say, C++ or JAVA.

[as3]
var i:* = {};
i = 7.4;
i = “11”
i = new iClass();
//All these are fine as i is an untyped(*) variable.
[/as3]

Another reason for why ActionScript 3 is still not a truly Nun/strictly typed language is its ability to create objects, classes and associative arrays on the fly. Consider the following code.

[as3]
var i:Object = [];
i.push({a:”b”, c:4}, 123, new Dictionary());
trace(i); //Outputs [object Object],123,[object Dictionary]
[/as3]

Belonging to the family of ECMA languages, its purpose is obvious. It serves as a Front-End technology to run on the client and when compared with JavaScript it runs in a plug-in compiled to bite-code as apposed to compilation onLoad then execution, but that’s a different topic…

To a logical mind, there is only one nothing, or null value. But undefined holds a very special place in the hearts of front end development. Say you’re loading a feed from some web-service out there on the “internets”, and you’re not quite sure what to expect, this is a common scenario where undefined would come into play. There are tons of techniques on how to handle similar situations, but if you want to preserve the integrity of your run-time constants, simply checking against an empty String isn’t the best of practices.

Code Explained

NULL: In this example, the variable “i” is null, as it has not yet been instantiated with any values. This is a common occurrence when we create new classes with all their corresponding properties but forget to associate them with any value.

[as3]
var i:Object;
trace(i); //Outputs null
i = {};
trace(i); //Outputs [object Object]
[/as3]

UNDEFINED: In this example, the property “e” of variable “i” is undefined, as “e” has not yet been instantiated.

[as3]
var i:Object = {a:”b”, c:”d”};
trace(i.e); //Outputs undefined
i.e = “f”;
trace(i.e); //Outputs f
[/as3]

It’s worth noting that back in ActionScript 2, null didn’t exist. So simply declaring and not instantiating a variable wouldn’t result in an undefined.

Posted in Flash AS3, Syntax | Tagged , , , | Comments Off on AS3 undefined vs null

Bitwise Operations in ActionScript 3

We – Flash Engineers – rarely use these operators, but when we do, performance and efficiency are in mind.  Bitwise operators are used to manipulate bits of data/variables, they operate on single or sets/pairs of bits – otherwise known as bit patterns – at the level of their individual bits.

There are two types of bitwise operations; bitwise operators and bitwise shifts.
Bitwise Operators consist of the NOT, OR, XOR and AND.  Bitwise Shifts consist of the Arithmetic, Logical, Rotary No Carry and Rotary Carry Through.  One note on bitwise shifts is that they are sometimes considered bitwise operations, because they operate on the binary representation of its numberical value, but the bitwise shifts do not operate on pairs like the bitwise operators, and therefore cannot be considered bitwise operations, but bitwise nonetheless.

As indicated earlier, bitwise operators manipulate bits of unsigned integers.  Let’s look at some examples, by the way, put on your binary goggles.

So let’s say we have these constant variables.

[as3]
private const A:uint = 1; //00000001
private const B:uint = 2; //00000010
private const C:uint = 4; //00000100
private const D:uint = 8; //00001000
private const E:uint = 16;//00010000
private const F:uint = 32;//00100000
[/as3]

Bitwise Operators

NOT: Bitwise NOT(~), or the compliment operator, is a unary operation that performs a logical negation on each individual bit in a bit pattern, so, 0’s become 1’s and vise-versa. This operator will convert the number into a signed 32-bit integer and then performs a bitwise One’s Complement; and when converting unsigned numbers the Two’s Complement is performed.

[as3]
//Example 1
trace(~A); //outputs -10 – decimal -2
//Example 2
trace(~-B); //outputs 01 – decimal 1
[/as3]

OR: Bitwise OR(|), takes 2 bit patterns of the same length and processes them by performing a logical inclusive OR on each pair. In each pair the result is 1 if the first or second or both bits are 1, otherwise double 0’s are 0.
[as3]
//Example 1
trace(C | D); //outputs 00001100 – decimal 12
//Example 2
trace(E | F); //outputs 00110000 – decimal 48
[/as3]

XOR: Bitwise XOR(^), exclusive OR, performs a logical XOR on each pair of bits. The result in each position is 1 if the two bits are different and 0 if they’re the same.
[as3]
//Example 1
trace(A ^ B); //outputs 00000011 – decimal 3
//Example 2
trace(C ^ D); //outputs 00001100 – decimal 12
[/as3]

AND: Bitwise AND(&), performs a logical AND on each pair of bits. In each pair, the result is 1 if both bits are 1, otherwise it’s 0.
[as3]
//Example 1
trace(C & D); //outputs 00000000 – decimal 0
//Example 2
trace(E & F); //outputs 00000000 – decimal 0
[/as3]

Bitwise Shifts

For good reason, bitwise shifts are sometimes considered bitwise operations, since they operate on the binary level of a numeric/unsigned integer. However, bitwise shifts don’t operate on sets or pairs of bits, rather on entire register sets. In this type of operation, the register digits are moved or shifted to either left or right. So, these registers have a fixed number of slots, and when a set of digits are shifted either direction, we are left with the tail to deal with. There are four types of shifts, Arithmetic, Logical, Rotary No Carry and Rotary Carry Through. Bitwise shifts are another rare usage case in ActionScript 3, we can use these operation to manipulate graphics and color information.

Arithmetic Shift: in an arithmetic shift, the bits are discarded from either end they are shifted. For instance, in a left shift, zeros are filled in on the right, but in a right shift the sign bit is placed in the left or beginning of the register to preserve the sign or handle.

Logical Shift: a logical shift is very similar to the arithmetic shift in that when you shift the digits, zero’s are filled into the void. So they perform exactly the same operation, it just that the logical will set 0’s on either end of the digits instead of setting the sign bit to the left when performing a right shift.

Rotate No Carry: also known as the circular shift or bit rotation, shifts the bits as if the left and right ends of the registry were connected, sort of like a length modulated carousel.

Rotate Carry Through: is very similar to the Rotate No Carry shift where the two ends of the register and seperated by the carry flag or otherwise known as the C flag. The bit that is shifted in – on either end – becomes the old value of the C flag, and the bit that is shifted out becomes the new value of the C flag. We’ve all been through this is 2nd grad math and in accounting classes. Carry/borrow the number in additions and LIFO & FIFO.

AS3 Shifting: ActionScript, and other C Like languages and can perform bitwise shifts. The syntax is the same, with varied applications. In C and C++ the bitwise shift operators perform logical shifts on unsigned integers, in Java and AS3 they perform arithmetic and logical shifts on signed integers. The syntax for left and right shifts are “<<” and “>>” respectively, which perform arithmetic shifts. There’s also the “>>>” operator for logical shifts but since the logical and arithmetic left shifts are identical, there’s no need for a “<<<“, which doesn’t exist in the language.
[as3]
var x:uint = 1, y:uint = 2, z:uint = 3;
trace(x = y << z); //Shifts three bits to the left – outputs 16
[/as3]

Just like with operators there aren’t much applications for the shifters. However, if you’re looking for fast computations like for simulations or games, you might want to brush up on some of these bitwise techniques.

For instance, if you wanted to get the square root or multiply by any power of two to any number you might want to left shift like this:
[as3]
var x:uint = 2;
trace(x = x * 2); //Outputs 4
trace(x = x * 256); //Outputs 1024
//Same as
x = 2;
trace(x = x << 1); //Outputs 4
trace(x = x << 8); //Outputs 1024
[/as3]

Or if you wanted to divide by any power of two, you can do something like this.
[as3]
var x:uint = 2;
trace(x = x / 2); //Outputs 1
trace(x = x / 8); //Outputs 0.125
//Same as
x = 2;
trace(x = x >> 1); //Outputs 1
trace(x = x >> 8); //Outputs 0
[/as3]

Say you wanted to convert a Number/Float into a signed integer. You can do this:
[as3]
var x:uint;
trace(x = int(1.234)); //Outputs 1
//Same as
trace(x = -1.234 >> 0); //Outputs -1
[/as3]

I’m sure we’ve all wanted to swap values, but had to use some sort of temporary variable to hold the value. We do this using the bitwise XOR assignment(^=).
[as3]
var a:int = 5;
var b:int = 10;
var t:int = a;
trace(a = b); //Outputs 10
trace(b = t); //Outputs 5
//Same as
a = 5;
b = 10;
trace(a ^= b); //Outputs 15
trace(b ^= a); //Outputs 5
trace(a ^= b); //Outputs 10
[/as3]

Sometimes we need to convert negative number to positive and vise versa, this is also known as sign flipping. Get it? sign and unsign?
[as3]
x *= -1; //Regular way.
//Flip
x = ~x + 1;
//or
x = (x ^ -1) + 1;
[/as3]

We’re constantly incrementing or decrementing values. Now this procedure is not necessarily faster nor does it require less typing, but it’s an option that’s on the table. As far as speed goes, pre vs. post. pre is slightly faster.
[as3]
//increment/decrement
x = -~x; // x++
x = ~-x; // x–
[/as3]

If you needed to extract color values from each component, you would do something like this.
[as3]
//24bit
var color:uint = 0x003366;
var r:uint = color >> 16; //Outputs 0
var g:uint = color >> 8 & 0xFF;//Outputs 51
var b:uint = color & 0xFF; //Outputs 102
[/as3]

[as3]
//32bit
var color:uint = 0xFF003366;
var a:uint = color >>> 24; //Outputs 255
var r:uint = color >>> 16 & 0xFF; //Outputs 0
var g:uint = color >>> 8 & 0xFF; //Outputs 51
var b:uint = color & 0xFF; //Outputs 102
[/as3]

We can reverse engineer the previous calculations and combine the color components.
[as3]
//24bit
var r:uint = 0x00;
var g:uint = 0x33;
var b:uint = 0x66;
var color:uint = r << 16 | g << 8 | b; //Outputs 13158
[/as3]

[as3]
//32bit
var a:uint = 0xFF;
var r:uint = 0x00;
var g:uint = 0x33;
var b:uint = 0x66;
var color:uint = a << 24 | r << 16 | g << 8 | b; //Outputs 4278203238
[/as3]

Posted in Binary, Flash AS3 | Tagged , , , , , | 3 Comments

Hello World in Java

I’m getting ahead of myself. I can’t wait for the book to arrive so I’ve been reading up the “WikiPedias” about Java and successfully setup Eclipse and ran a Hello World program. It’s not much, but it’s one step closer to kickin’ ass!

[java]
// Outputs “Hello, world!” and then exits
public class HelloWorld{

//private static HelloWorld helloWorld;
private String helloText = “Hello World”;
private String byeText = “Bye”;

public static void main(String[] args) {
System.out.println(“Entering”);

HelloWorld helloWorld = new HelloWorld();
helloWorld.init();
}

public HelloWorld()
{
System.out.println(helloText);
}

private void init()
{
byeText += ” World”;
byeWorld();
}

private void byeWorld()
{
System.out.println(byeText);
}
}
[/java]

I trying to get the hang of the whole public static void main function; everything is making sense to me, it’s just that it’s a slow process.

Posted in JAVA | Tagged , , , , , | Comments Off on Hello World in Java

Learning JAVA

Yep, I’ve just ordered the Head First JAVA book and will be diving”head first” into JAVA.  Anyway I look at it, JAVA is becoming the main development platform with its common work-flow and cross-compilers to accommodate different environments. I can’t wait for the book to arrive…

Posted in JAVA | Tagged | 1 Comment

AS3 Array vs Vector

Another great new feature of AS3 and Flash Player 10 is the Vector Class.  Vectors are a lot like Arrays, in that they’re unsorted lists which can hold values/variables – with one caveat – they can only hold one type of variable. Vectors are otherwise known as typed Arrays or strict lists.  While normal Arrays can hold multiple types of variables, Vectors can hold a single type of variable, oh and did I mention they can be fixed?

This is how we normally declare Arrays:

[as3]
var array:Array = new Array();
//or
var array:Array = [];
[/as3]

And/so this is how we declare Vectors:

[as3]
var vector:Vector.<uint> = new Vector.<uint>();
//or
var vector:Vector.<uint>;
vector = new Vector.<uint>();
[/as3]

This kind of behavior can greatly increase the performance of the script running in the AVM. With no extra conditioning or checksumming in memory to access the elements, this strictly typed “Array” can perform all your list tasks with great ease. Also, we’re not limited to casting our vectors to primitive types like Numbers and Strings, you can cast to any custom type you want. However, the base types must match exactly, inherited types are not allowed either. For example, even though Sprite is a subclass of DisplayObject, it won’t compile. See example below.

[as3]
//Won’t compile
var vector:Vector.<DisplayObject> = new Vector.<Sprite>();

//Will compile
var vector:Vector.<Sprite> = new Vector.<Sprite>();
[/as3]

This type of variable declaration is obviously a little unorthodox, but it has its reasons… At this point, we should only keep in mind that it’s known as “postfix type parameter syntax”.

If you’re like me, you like to shorthand your declarations whenever possible, so If you used to do.

[as3]
var array:Array = [1, 2, 3, 4, 5, 6, 7];
[/as3]
you can equally do
[as3]
var vector:Vector.<uint> = Vector.<uint>([1, 2, 3, 4, 5, 6, 7]);
[/as3]

Notice the absence of the “new” keyword, for all obvious reasons, and if it’s not obvious to you, it’s because the constructor will return a new instance anyway.

As mentioned earlier, Vectors are a lot like Arrays, you can pop, push, shift, unshift, sort… to manipulate the lists elements. Just like an Array, when passed as the first argument to the Vector constructor, Vectors can be initialized with a specific size or length. Additionally, when passed as a Boolean in the second argument, Vectors can be fixed, sort of like a constant length, so you have to be careful not to go over board/bounds with your pops and pushes. By default, the length is set to zero or unlimited and they’re not fixed rather set to false.

[as3]
/*
Will throw a RangeError.
I’m declaring a variable called vector, with 10 elements and setting fixed to true.
If fixed were set to falsewe wouldn’t get any errors, as we are not limited to
the number of elements allowed.
*/
var vector:Vector.<uint> = new Vector.<uint>(10, true);
vector.push(1);
[/as3]

For more info on Vectors, check out the Adobe site on it.
http://help.adobe.com/en_US/AS3LCR/Flash_10.0/Vector.html

Posted in Array, Flash AS3, Syntax, Vector | Tagged , , , , , , | 12 Comments

Flash Logging through FireBug!

FireBug Sample OutputThis – Thunderbolt – is seriously an invaluable resource for all Flash Engineers.  Well, that’s if you use FireBug with FireFox, and c’mon, who doesn’t nowadays? So basically, all you have to do is import the “Logger” class and log messages, then those messages appear in the Console tab in FireBug.  Thunderbolt is great because as Flash Engineers, we’re constantly having to prove exceptions and make cases to QA.

Other than just logging, which it does on so many different levels – it provides memory snapshots, application stats and so much more. It works with Flash CS(X), Flex(X), Air(X) and even comes with an external output panel/console.

Check this switch out… enough said.
Get it here, http://code.google.com/p/flash-thunderbolt/downloads/list.

[as3]
switch (label)
{
case “info”:
Logger.about();
Logger.info(“FLash is calling: A simple string”, myString);
break;
case “warn”:
Logger.warn (“FLash is calling: Two log objects: A number typed as int and a string”, myNumber, myString);
break;
case “error”:
Logger.error (“FLash is calling: An array with a nested object: “, myArray);
break;
case “debug”:
Logger.debug (“FLash is calling: An object with a nested object and nested array”, myObject);
break;
case “memory”:
Logger.info(“FLash is calling: ” + Logger.memorySnapshot());
break;
default:
Logger.error (“FLash is calling: No button found with a label called ” + label);
}
};
[/as3]

Thanks to Jens Krause

Posted in Flash AS3, Logging | Tagged , , , | Comments Off on Flash Logging through FireBug!

Global.as

[as3]
/** ———————————————————–
* Class Name: Global.as
* ————————————————————
* Description: Global(Singleton) is a sort of _global where
* all global vars – including FlashVars – and functions exist.
* ————————————————————
* Created by: Bobby Berberyan – 09.09.09
* Modified by:
* Date Modified:
* ————————————————————
* Copyright ©2009 FOX SPORTS Interactive
* For license and usage information, please review the company
* or News Corp manual.
* ————————————————————
* Usage: Global.vars.name = value;
* ————————————————————
*
*/
package utils
{
import flash.display.LoaderInfo;
import flash.net.URLRequest;
import flash.net.navigateToURL;

import utils.ExternalInterfaces.BasicExternalInterface;
import utils.HTTPCookies.HTTPCookie;
import utils.SharedObjects.BasicSharedObjects;
import utils.Tweeners.BasicTween;
import utils.loaders.data.DataLoader;
import utils.loaders.media.MediaLoader;

public class Global extends Object
{
private static var _dataLoader:DataLoader;
private static var _mediaLoader:MediaLoader;
private static var _basicExternalInterface:BasicExternalInterface;
private static var _basicSharedObject:BasicSharedObjects;
private static var _basicTween:BasicTween;
private static var _httpCookies:HTTPCookie;
public static var vars:Object = {};

//Ingests the FlashVars in the Global Var too.
public static function getFlashVars():void
{
var varsAll:String = “”;
var varName:String;
var paramObj:Object = LoaderInfo(vars.root.loaderInfo).parameters;
for (varName in paramObj)
{
vars[varName] = String(paramObj[varName]);
}
}
[/as3]

No more…

Posted in Flash AS3 | Comments Off on Global.as

Why there’s no Flash on the iPhone

I knew it(profits) to be the case all along, but this totally solidified my suspicions. It’s a new ad system from Apple called iAd. Check it out, http://en.wikipedia.org/wiki/IAd.

Posted in Flash AS3 | Tagged , , , | Comments Off on Why there’s no Flash on the iPhone

Flash Engineer vs Developer

Flash Professional CS5 Art

Flash Professional

What it means to be a Flash Engineer vs Developer, well, it means a lot.  Developers are so…..

Posted in Flash AS3 | Tagged | Comments Off on Flash Engineer vs Developer