First of all, just installed the wp-syntax plugin, so now we can have proper example code on the blog. I can’t believe it took us so long to get it on here, seen as its pretty much ubiquitous among the developer community, I find it really useful when browsing example sites so I thought we better get it on here sharpish.
Will that in mind I thought I’d share a particular hack/workaround that I was working with last week regarding for..in loops (not to be confused with for each loops).

1
2
3
4
for (var i : * in object)
{
 
}

This works fine for native objects and arrays, but back in the day of as2 you could loop over public variables and getters in custom classes as well. Not so in as3, it simply skips the loop. As you may have guessed by the title of this post the solution is to override the default valueOf() function with an object that represents your class, for example.

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
package {
 
	/**
	 * @author alexanderfell
	 */
	public class GeomPoint {
 
		private var _dimensionMap:Array;
 
		public function GeomPoint(newDimensions:Array) 
		{
			_dimensionMap = newDimensions;
		}
 
		public function get x():Number
		{
			return _dimensionMap["x"];
		}
		public function get y():Number
		{
			return _dimensionMap["y"];
		}
		override public function valueOf():Object
		{
			return {x:x, y:y};	
		}
	}
}

This way, we simply loop over the valueOf() instead of the the class. As a side note the code above is for a co-ordinate generation system which may require the dimensions to be labelled differently depending on which frameworks we are using (for example APE uses “px” and “py”) which is the reason for all the dimensionMap funny business, not me being unnecessarily difficult.
The eagle-eyed design pattern enthusiast may be able to see the decoration of an array here (this is just an example, the real code has an abstract class that sets the dimensions, then everything extends that abstract…. what you think I’d put all the code up here!?).

edit: damn syntax styles….

Leave a Reply