<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>alecmce.com &#187; as3signals</title>
	<atom:link href="http://alecmce.com/tag/as3signals/feed" rel="self" type="application/rss+xml" />
	<link>http://alecmce.com</link>
	<description></description>
	<lastBuildDate>Thu, 10 Nov 2011 21:56:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Events and Signals &#8211; Performance Tests</title>
		<link>http://alecmce.com/as3/events-and-signals-performance-tests</link>
		<comments>http://alecmce.com/as3/events-and-signals-performance-tests#comments</comments>
		<pubDate>Tue, 26 Jan 2010 08:20:29 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[as3signals]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=673</guid>
		<description><![CDATA[The new as3signals library devised by Robert Penner offers a replacement to the native AS3 event model. One benefit is that signals are more lightweight, and therefore faster. Grant Skinner&#8217;s Performance Harness is a widely accepted library for comparing the speeds of code execution. I found the following results on Mac OS X, Flash Player [...]]]></description>
			<content:encoded><![CDATA[<p>The new <a href="http://github.com/robertpenner/as3-signals">as3signals library</a> devised by Robert Penner offers a replacement to the native AS3 event model. One benefit is that signals are more lightweight, and therefore faster. Grant Skinner&#8217;s <a href="http://www.gskinner.com/blog/archives/2009/04/as3_performance.html">Performance Harness</a> is a widely accepted library for comparing the speeds of code execution.</p>
<p>I found the following results on Mac OS X, Flash Player 10.0.42.34, with a <em>release build</em>.</p>
<p>When an event (signal) is dispatched but nothing is listening for it:</p>
<div style="text-align: center; margin: auto; padding: 10px;"><img src="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/01/results11.jpg" alt="A graph indicating that as3signals events dispatch roughly 5 times faster than native as3 events." width="357" height="262" /></div>
<p>When an event (signal) is dispatched and handled by one method listener:</p>
<div  style="text-align: center; margin: auto; padding: 10px;"><img src="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/01/results21.jpg" alt="A graph indicating that as3signals signals are dispatched and captured at twice the speed of native as3 events." width="357" height="265" /></div>
</p>
<p>The source code for my test methods follows:</p>
<ul>
<li><a href="http://gist.github.com/286640">Dispatching events without listeners</a></li>
<li><a href="http://gist.github.com/286642">Dispatching events with listeners</a></li>
</ul>
<p>If you browse these tests, you will notice that more tests were run than I have displayed above. The graphs above reference results from running the <code>dataEventOptimised</code> and <code>dataSignal</code> methods in each context.</p>
<p>These tests are not scientific. No attempt has been to control for player version, computer version, computer specifications, so on and so forth. You are invited to download and run these tests for yourself. If you do, remember that testing on a <em>release build</em> not a debug build is appropriate, and then please post your results as a comment, particularly if your results differ from my own.</p>
<h2>Updates</h2>
<p>For a comparison with good old fashioned callbacks, please put on your sarcasm snorkel and visit <a href="http://va.lent.in/blog/2010/01/27/omg-as3-signals-are-faster-than-events1">va.lent.in&#8217;s follow up post</a>.</p>
<p>From the <a href="http://groups.google.com/group/as3-signals/browse_thread/thread/3f9a203e6604b0f0?utoken=VwX81i4AAADzSqymN73RML18dAjSp6G6iJqNSdlwl88TjV7a-ukVihfEbSR7To5PnLe8EpnsVXE">as3signals Google Group</a> there was a suggestion that the Flash Player 10.1 might produce different results. Here are my results; they appear to corroborate the earlier results:</p>
<pre class="brush: plain; title: ; notranslate">
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
performancetests.EventsTest (5 iterations)
Player version: MAC 10,1,51,66 (regular)
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
dataEvent                                                  2344   468.80
dataEventOptimised                                         2270   454.00
dataSignal                                                  313    62.60
simpleEvent                                                2755   551.00
simpleEventOptimised                                       2285   457.00
simpleSignal                                                174    34.80
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
performancetests.CapturedEventsTest (5 iterations)
Player version: MAC 10,1,51,66 (regular)
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
dataEvent                                                  2708   541.60
dataEventOptimised                                         2703   540.60
dataSignal                                                 1182   236.40
simpleEvent                                                2724   544.80
simpleEventOptimised                                       2717   543.40
simpleSignal                                               1042   208.40
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
</pre>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/events-and-signals-performance-tests/feed</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>RobotLegsPong Part 1 &#8211; Overview</title>
		<link>http://alecmce.com/as3/robotlegspong1</link>
		<comments>http://alecmce.com/as3/robotlegspong1#comments</comments>
		<pubDate>Tue, 19 Jan 2010 07:01:23 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[as3signals]]></category>
		<category><![CDATA[asunit]]></category>
		<category><![CDATA[RobotLegs]]></category>
		<category><![CDATA[Ticker]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=649</guid>
		<description><![CDATA[Introduction RobotLegsPong attempts to combine RobotLegs application framework with the as3signals event model and a Frame-Ticker (as well as a pinch of ASUnit unit-testing) to create a &#8216;game&#8217;. It is an open-source project, available on GitHub as an example of using RobotLegs together with these other technologies. Source Code: github/alecmce/RobotLegsPong RobotLegsPong is not a very [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>RobotLegsPong attempts to combine RobotLegs application framework with the as3signals event model and a Frame-Ticker (as well as a pinch of ASUnit unit-testing) to create a &#8216;game&#8217;.</p>
<p>It is an open-source project, available on <a href="http://github.com/alecmce/RobotLegsPong/tree/master">GitHub</a> as an example of using RobotLegs together with these other technologies.</p>
<p style="text-align: center;">Source Code: <a href="http://github.com/alecmce/RobotLegsPong/tree/master">github/alecmce/RobotLegsPong</a></p>
<p>RobotLegsPong is not a very good <em>game</em>; it is playable only in the loosest sense. Bats require to be dragged in order to move (and there is no computer-logic to play against), so you could not really play against an opponent. The purpose of the exercise was to see what structure a game like Pong would take within the RobotLegs framework.</p>
<p>The purpose of this article is to describe the particulars of the technologies and why I chose them. In a follow-up article, I will look in more detail how RobotLegsPong is wired up.</p>
<h2>Why I Chose These Technologies</h2>
<h3>RobotLegs</h3>
<p>The RobotLegs framework is a lightweight, flexible application framework that allows coders to spend less time wiring up their application, and more time working on its functionality.</p>
<p>Frameworks are often criticised because they force developers to write code in a particular way, which might be inappropriate for a particular context. I have used Cairngorm, Pure MVC, as well as some proprietary frameworks, and have found that all of them do some things well, and do other things clumsily. So far I have not found this problem with RobotLegs, because most of the time it gets out of the way and lets you code; in fact, it does more than that: it reduces the amount of code you have to write.</p>
<h3>as3signals</h3>
<p>RobotLegs comes with an application event bus, but I have decided to circumvent that and use as3signals instead. as3signals allows you to define an object which acts as an event dispatcher within an application.</p>
<p>I like as3signals because describing an event as a Signal object allows my event model to be described through interfaces. as3signals is supposed to be fast too. Then again, interfaces are slow. The relative speeds of the approaches is interesting, but not a significant factor in my decision making process.</p>
<h3>Frame-Ticker</h3>
<p>The frame-ticker is a simple idea: rather than creating multiple enter-frame event listeners, each creating event objects, create one enter-frame listener and a main game loop iterating through those methods that need to be called per-iteration.</p>
<p>This implementation came out of a discussion on Twitter that I was involved in on the fringes; I wrote about it <a href="http://alecmce.com/as3/replacing-enter_frame">in a previous blog post</a>.</p>
<h3>ASUnit</h3>
<p>Unit testing enables developers to test portions of their code in isolation, so that they can be confident that every method works exactly as the developer intended. They also represent a secondary form of documentation-in-code; if you want to know how I meant a method to work, reading the unit test will tell you almost everything you need to know (including, if a good test is missing, what I <em>didn&#8217;t</em> consider).</p>
<p>That said, I have not unit tested every method; in this example I have only unit-tested the geometric logic for the bats. This is bad practice, however under time constraints I think that it is most important to unit test what is complex, mathematical or ambiguous, since this is where behaviour is most likely to fall down.</p>
<h2>[Inject]</h2>
<p>The &#8216;trick&#8217; to using RobotLegs is that you do not need to inject dependent objects into classes when you contruct them; this is done automatically. This code:</p>
<pre class="brush: as3; title: ; notranslate">
public class Dependee {}

public class MyExample
{
	public var dependee:Dependee;

	public function MyExample(dependee:Dependee)
	{
		this.dependee = dependee;
	}
}
</pre>
<p>becomes this code:</p>
<pre class="brush: as3; title: ; notranslate">
public class Dependee {}

public class MyExample
{
	[Inject]
	public var dependee:Dependee;
}
</pre>
<p>The metadata tag <code>[Inject]</code> has the effect of automatically injecting the dependee into the class when it is constructed. This isn&#8217;t much on the face of it, but it is enough. It feels to me as though a quarter of my code is actually just wiring up classes so that they each have access to the classes that they need to function, or passing objects around methods. The <code>[Inject]</code> tag lets me shift all of that wiring into the RobotLegs framework.</p>
<h2>Context</h2>
<p>There is a little more to the RobotLegs story however; how should RobotLegs react when it comes across an <code>[Inject]</code> tag? It could construct a new <code>Dependee</code> object, or it could be that I want only one <code>Dependee</code> object to be injected wherever the <code>[Inject]</code> tag is found. This is where the <code>Context</code> class becomes meaningful.</p>
<p>In the <a href="http://github.com/alecmce/RobotLegsPong/blob/master/src/app/PongContext.as">PongContext</a>, different classes are wired up in different ways. Their definitions are defined by adding <code>injector</code> mappings and the <code>mediatorMap</code> mappings in the <code>startup</code> method.</p>
<pre class="brush: as3; title: ; notranslate">
public class PongContext extends Context
{
	override public function startup():void
	{
		...
		injector.mapSingleton(DragMechanism);
		injector.mapSingletonOf(Geometry, GeometryModel);
		injector.mapClass(BatGeometry, BatGeometryModel);
		...
	}
}
</pre>
<h3>injector.mapSingleton</h3>
<pre class="brush: as3; title: ; notranslate">injector.mapSingleton(DragMechanism)</pre>
<p><code>mapSingleton</code> indicates that only one instance of the class entered should be constructed. In this case, just one <code>DragMechanism</code> will be created, and injected whenever this is found:</p>
<pre class="brush: as3; title: ; notranslate">
[Inject]
public var mechanism:DragMechanism;
</pre>
<h3>injector.mapSingletonOf</h3>
<pre class="brush: as3; title: ; notranslate">injector.mapSingletonOf(Geometry, GeometryModel);</pre>
<p><code>mapSingletonOf</code> extends the <code>mapSingleton</code> idea to interfaces and their implementing classes. In this case the <code>Geometry</code> interface is mapped to the <code>GeometryModel</code> class. The injection is called as follows:</p>
<pre class="brush: as3; title: ; notranslate">
[Inject]
public var model:Geometry;
</pre>
<p>No reference to the <code>GeometryModel</code> is needed in any class other than the <code>PongContext</code>. This allows a very pure use of interfaces across the application.</p>
<h3>injector.mapClass</h3>
<pre class="brush: as3; title: ; notranslate">injector.mapClass(BatGeometry, BatGeometryModel)</pre>
<p><code>injector.mapClass</code> works a little differently; whenever a <code>BatGeometry</code> interface is flagged to be injected, a new instance of <code>BatGeometryModel</code> is constructed and injected into the class, so the following code is used to create the injection:</p>
<p>Each <code>BatMediator</code> needs its own <code>BatGeometry</code> object. By using the <code>mapClass</code> method, multiple <code>BatGeometryModel</code> objects will be constructed, one for each time the following code is found:</p>
<pre class="brush: as3; title: ; notranslate">
[Inject]
public var model:BatGeometry;
</pre>
<h2>Mediators and Components</h2>
<pre class="brush: as3; title: ; notranslate">
public class PongContext extends Context
{
	override public function startup():void
	{
		...
		mediatorMap.mapView(Background, BackgroundMediator);

		addChild(new Background());
	}
}
</pre>
<p><code>mediatorMap</code> references a slightly different aspect of the application: your view objects. The <code>mediatorMap</code> allows users to define associations between display objects and <code>Mediator</code>s. These two parts comprise the <em>View</em> aspect of the standard MVC pattern.</p>
<p>The <code>DisplayObject</code> &#8211; in this case <code>Background</code> &#8211; is the asset that you want to be visible on the stage. In my pong example this is essentially just a Sprite, though it might just as well have been imported as a graphical asset in a SWC.</p>
<p>The <code>Mediator</code> is associated with the <code>DisplayObject</code> so that when an instance of the <code>DisplayObject</code> is created, the corresponding <code>Mediator</code> is also constructed. The <code>BackgroundMediator</code> looks something like this:</p>
<pre class="brush: as3; title: ; notranslate">
public class BackgroundMediator extends Mediator
{
	[Inject]
	public var view:Background;

	override public function onRegister():void
	{
		...
	}
}
</pre>
<p>The <code>DisplayObject</code> <code>Background</code> is injected into the <code>BackgroundMediator</code> when it is constructed. The <code>DisplayObject</code> can then be manipulated. It is an elegant solution that separates display object from UI logic.</p>
<pre class="brush: as3; title: ; notranslate">addChild(new Background());</pre>
<p>is all that is needed to wire the entire <code>DisplayObject</code>/<code>Mediator</code> combination.</p>
<h3>RobotLegs &#038; Tickers</h3>
<p>The RobotLegs structure is particularly useful for wiring up a <code>Ticker</code>-based application because one ticker can be mapped as a singleton, and injected to all those methods that need to iterate every frame:</p>
<pre class="brush: as3; title: ; notranslate">
public class PongContext extends Context
{
	override public function startup():void
	{
		...
		injector.mapSingletonOf(Ticker, EnterFrameTicker);
		...
	}
}
</pre>
<h3>RobotLegs with as3signals</h3>
<p>I really like the style of event dispatching that <code>as3signals</code> provides, but my implementation demands that if one class requires another class then it must flag it to be injected, and then the signal wired up in a method flagged as <code>[PostConstruct]</code> (see <a href="http://github.com/alecmce/RobotLegsPong/blob/master/src/app/model/GeometryModel.as">GeometryModel</a>). This doesn&#8217;t feel like the right solution.</p>
<p>Integrating <code>as3signals</code> with RobotLegs is beyond the scope of this article. It looks like Joel Hooks and Robert Penner are making inroads into this problem through <a href="http://groups.google.com/group/as3-signals/browse_thread/thread/fabc7995e9e55ec3#">as3signals&#8217; Google Group</a>. I look forward to seeing what they come up with.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/robotlegspong1/feed</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Replacing ENTER_FRAME</title>
		<link>http://alecmce.com/as3/replacing-enter_frame</link>
		<comments>http://alecmce.com/as3/replacing-enter_frame#comments</comments>
		<pubDate>Thu, 26 Nov 2009 23:37:30 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[as3signals]]></category>
		<category><![CDATA[compiler]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[mxmlc]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=552</guid>
		<description><![CDATA[Today an interesting discussion took place on Twitter, in which I was involved. It caught my attention for a variety of reasons, and I wanted to document the conversation, the problem and the solution here. It started when it was identified that Flash&#8217;s event dispatcher is sub-optimal in performance terms, and revolved around trying to [...]]]></description>
			<content:encoded><![CDATA[<p>Today an interesting discussion took place on Twitter, in which I was involved. It caught my attention for a variety of reasons, and I wanted to document the conversation, the problem and the solution here. It started when it was identified that Flash&#8217;s event dispatcher is sub-optimal in performance terms, and revolved around trying to find a solution.</p>
<h2>Why replace the ENTER_FRAME?</h2>
<p>Every event that is dispatched creates an object. An ENTER_FRAME creates as many objects per second as there are frames. If you have mutliple objects dispatching ENTER_FRAME events, that&#8217;s many objects creating event objects many times per second. Computationally, chains of &#8220;many&#8221; are one of those things you want to avoid. So, can we do better?</p>
<h2>Doing Better</h2>
<p>Robert Penner proposed creating an as3signal and using a MovieClip with two frames to dispatch that signal on each frame. He posted his idea to <a href="http://gist.github.com/243630">this GitHub gist</a>.</p>
<p>One drawback to this approach is that it requires a MovieClip symbol with two empty frames, to which the two event dispatcher methods could be attached. I remembered reading in <a href="http://www.bit-101.com/blog/?p=946">this excellent article by Bit 101</a> how using a [Frame] metadata tag would force your application to have two frames. This seemed to be what Penner needed for his functionality to work correctly, so I came up with <a href="http://gist.github.com/243692">my own GitHub gist</a> which extends the concept. The code is also added &#8216;<a href="#fold">below the fold</a>&#8216;, at the bottom of this article.</p>
<p><em>[Update, after <a href="http://alecmce.com/as3/replacing-enter_frame#comment-24152811">Jackson's comment</a>, below]</em> The idea behind the approach is that a frame-loop is an internal Flash player structure. It sits underneath the AS3 functionality, and so it doesn&#8217;t produce ENTER_FRAME events. By hooking into them we can produce our own iterative &#8216;event&#8217; (Penner proposes using an as3signal), which doesn&#8217;t construct an object each time it is dispatched. It is a lovely idea, and quite distinct from invoking one ENTER_FRAME dispatcher on the root or stage of the application.</p>
<p><em>[Update, after <a href="http://alecmce.com/as3/replacing-enter_frame#comment-24168332">Joa Ebert tweeted test results</a>]</em> Whether this method is superior to the &#8216;one-event ticker&#8217; is open to question. Joa Ebert applied the frameloop concept to AudioBox and found no memory nor performance improvements.</p>
<h2>Background</h2>
<p>It all started today with a statement on Twitter from Robert Penner:</p>
<blockquote><p>Listening to a single #AS3 enterFrame will create over 1000 event instances per minute. <em><a href="http://bit.ly/5A36ZS">@robpenner</a></em></p></blockquote>
<p>In fact, at a decent frame rate, you&#8217;re looking at 1800 event instances per minute. Across the blogosphere and on Twitter, there has been a lot of talk about the cost of object construction in AS3. People are pushing the limitations of the player, and are looking for performance optimisation wherever they can find it. Strategies such as object pooling are becoming mainstream in order to avoid the creation and destruction of objects. In the meanwhile, the internal Flash event model is creating and destroying huge numbers of objects to furnish us with an event model.</p>
<p>At the same time however, there has been a murmur of discomfiture about the state of the event model. (Not that I have much of a voice, but I <a href="http://alecmce.com/opinion/as4-thought-experiment">chimed in to this debate</a> as well!). The most notable result of this murmur was Penner&#8217;s decision to create <a href="http://github.com/robertpenner/as3-signals">as3signals</a>. It is an on-going project to which I have contributed in a small way, and which I whole-heartedly support.</p>
<p>After Penner&#8217;s tweet, the <a href="http://twitter.com/alecmce/flashdevs">#as3 twitterati</a> (please tweet if there are glaring omissions from this list) became very excited indeed.</p>
<p>My initial thoughts led to the idea that maybe the setInterval/setTimeout functions, which are hangovers from AS2 might offer a solution &#8211; perhaps they shortcut the event system? Not only ain&#8217;t it so, they&#8217;re even worse <a href="http://bit.ly/4E1Unk">as this Action Script Viewer deconstruction of the setInterval methods</a> demonstrate.</p>
<p>So what else? Mike Chambers (aka <a href="http://twitter.com/mesh">@Mesh</a>) in conversation with <a href="http://twitter.com/theflashbum">@TheFlashBum</a> pointed towards <a href="http://bit.ly/7NK8hQ">a solution using a &#8216;ticker&#8217;</a>; a single ENTER_FRAME dispatcher, and <a href="twitter.com/bengarney">@bengarney</a> confirmed that <a href="http://bit.ly/8iKdQC">he also uses this technique</a>.</p>
<p>It seems that @scottjanousek and @robpenner had the idea of using the player frameloop (which the solution offered here exploits) at pretty much the same time. (@scottjanousek&#8217;s tweets are protected, but it was reported by <a href="http://bit.ly/4ZdU1Q">this tweet</a>.)</p>
<p>Whether and how this vein of thought will develop is really interesting. It is fascinating how a tweet from one of the best-known ActionScript developers can provoke such a lot of attention from the general community. It is interesting too to see the envelope of what is possible being pushed.</p>
<p><span id="more-552"></span></p>
<h2><a name="fold">FrameLoop Example Source Code</a></h2>
<p>To use this code, you will need the <a href="http://github.com/robertpenner/as3-signals">as3signals</a> library. You will also need to compile through the MXML compiler. I have tested it with the Flex 4 SDK &#8211; if you try and discover that it does not work for other target platforms, please share the information by leaving a comment!.</p>
<h3>Main.as</h3>
<pre class="brush: as3; title: ; notranslate">
package
{
	import org.osflash.signals.Signal;

	import flash.display.Shape;
	import flash.display.Sprite;

	/**
	 * A Main application class that uses the [Frame] MetaData Tag to use the
	 * EventFrameDispatcher class to configure itself. This class contains a
	 * frame signal which is constructed and passed into it by the
	 * EventFrameDispatcher class before init() is called. Application
	 * functionality should be placed in the init() method
	 *
	 * @author Alec McEachran
	 */
	[Frame(factoryClass=&quot;EnterFrameDispatcher&quot;)]
	public class Main extends Sprite
	{
		/** an as3signal that is dispatched on every ENTER_FRAME */
		public var frame:Signal;

		/**
		 * do interesting things in here...
		 */
		public function init():void
		{
			// functionality here...
		}
	}
}
</pre>
<h3>EnterFrameDispatcher.as</h3>
<pre class="brush: as3; title: ; notranslate">
package
{
	import org.osflash.signals.Signal;

	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.utils.getDefinitionByName;

	/**
	 * The EnterFrameDispatcher is injected into the Main class through
	 * the [Frame] MetaData tag.
	 *
	 * The class creates a frame signal. By being injected, two frames are
	 * generated, onto which the frameMethod are attached so that the
	 * frame signal is dispatched on every frame cycle. It then injects this
	 * object into the Main class and calls the Main class's init() method.
	 *
	 * @author Alec McEachran
	 *
	 * based on an idea by Robert Penner @see http://gist.github.com/243630
	 */
	public class EnterFrameDispatcher extends MovieClip
	{
		public var frame:Signal;

		public function EnterFrameDispatcher()
		{
			frame = new Signal();
			addFrameScript(0, frameMethod, 1, frameMethod);

			addEventListener(Event.ENTER_FRAME, onEnterFrame);
			nextFrame();
		}

		private function onEnterFrame(event:Event):void
		{
			removeEventListener(Event.ENTER_FRAME, onEnterFrame);
			init();
			play();
		}

		private function frameMethod():void
		{
			frame.dispatch();
		}

		private function init():void
		{
			var mainClass:Class = Class(getDefinitionByName(&quot;Main&quot;));
			if (mainClass)
			{
				var app:* = new mainClass();
				app.frame = frame;
				addChild(app);
				app.init();
			}
		}
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/replacing-enter_frame/feed</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>Reflecting on as3signals</title>
		<link>http://alecmce.com/as3/reflecting-on-as3signals</link>
		<comments>http://alecmce.com/as3/reflecting-on-as3signals#comments</comments>
		<pubDate>Tue, 06 Oct 2009 07:59:10 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[as3signals]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=363</guid>
		<description><![CDATA[Robert Penner has recently produced a new AS3 library called as3signals (which can be found on both Git Hub and Google Code. I have used it in one small ongoing project, and I am really impressed with it. as3signals includes two methods for adding listeners: an add listener which permanently adds a listener until a [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.robertpenner.com/flashblog/">Robert Penner</a> has recently produced a new AS3 library called as3signals (which can be found on both <a href="http://github.com/robertpenner/as3-signals">Git Hub</a> and <a href="http://code.google.com/p/as3-signals/">Google Code</a>. I have used it in one small ongoing project, and I am really impressed with it.</p>
<p>as3signals includes two methods for adding listeners: an <code>add</code> listener which permanently adds a listener until a <code>remove</code> listener is called, and an <code>addOnce</code> listener which is a one-time listener only. This is a really welcome addition to the event model. Current projects are littered with code like this:</p>
<pre class="brush: as3; title: ; notranslate">
objectThatDispatchesEvent.addEventListener(EventType, onEvent, [false, 0, true]);

private function onEvent(event:Event):void
{
	objectThatDispatchesEvent.removeEventListener(EventType, onEvent);
	...actual code for handling event...
}
</pre>
<p>Penner&#8217;s signals performs the task much more neatly:</p>
<pre class="brush: as3; title: ; notranslate">
signal.addOnce(onEvent);

private function onEvent(data:Data):void
{
	...actual code for handling event...
}
</pre>
<p>An interesting problem arises by having two methods for adding listeners that have different behaviours. What happens when you call first one, then the other, without calling a <code>remove</code> method in between? There are three main ways in which you could imagine the framework responding to this situation.</p>
<ol>
<li><strong>Overwrite Model</strong> Each time a call redefines the relationship between signal and listener. In this model, subsequent calls overwrite the relationship;</li>
<li><strong>First-Wins Model</strong> The first call defines the relationship between signal and listener. In this model, subsequent calls are ignored. To change the relationship the current relationship should be first removed;</li>
<li><strong>Throw Error Model</strong> If you attempt to change the relationship between signal and listener without first calling <code>remove</code> then an error is thrown.</li>
</ol>
<h2>Overwrite Model</h2>
<p>The <code>add</code> method defines a stronger relationship between signal and listener than the <code>addOnce</code> method. If I had previously called <code>signal.addOnce(listener)</code> and then called <code>signal.add(listener)</code>, I am intentionally strengthening the signal-listener relationship, and want the relationship to <em>change</em>. Conversely, I would expect the relationship to weaken.</p>
<p>A weakness of this model is that if you were to inadvertently change the relationship between the signal and listener, this would be extremely difficult to debug.</p>
<h2>First-Wins Model</h2>
<p>If you assign an event listener with <code>addEventListener</code> in the as3 native event model then you assign a priority to the listener which defines the order in which listeners are called (an optional parameter, which is 0 by default). In the as3 native event model, you cannot change the listener priority with further <code>addEventListener</code> calls unless you first call <code>removeEventListener</code>. Subsequent listener priorities are ignored. Similarly then, we could take this approach for <code>add</code> and <code>addOnce</code>. All subsequent calls are ineffective unless <code>remove</code> is called.</p>
<p>A weakness of this model is that if you intentionally change the relationship between the signal and listener, then your change should be effective! The following code certainly looks like it should work, but in fact the second line does nothing at all!</p>
<pre class="brush: as3; title: ; notranslate">
signal.addOnce(listener);
signal.add(listener);
</pre>
<h2>Throw Error Model</h2>
<p>There are scenarios in which developers might purposefully use both <code>add</code> and <code>addOnce</code> methods without calling a <code>remove</code> method in between. However, there will likely be cases where the two methods are called interchangeably by mistake. This may not be easy to debug, and we could easily help the developer out here by changing the functionality so that if <code>signal.addOnce(listener)</code> and <code>signal.add(listener)</code> are called in either order without an intervening <code>signal.remove(listener)</code>, that an error is thrown.</p>
<p>In many ways, this is an extension of the &#8216;first-wins model&#8217;, because it preserves the functionality of that model. However, it recognises that the developer that intends to change behaviour might write something like:</p>
<pre class="brush: as3; title: ; notranslate">
signal.addOnce(listener);
signal.add(listener);
</pre>
<p>and handles it by throwing an error. The developer can then quickly change his code to either simply</p>
<pre class="brush: as3; title: ; notranslate">
signal.addOnce(listener);
</pre>
<p>or</p>
<pre class="brush: as3; title: ; notranslate">
signal.addOnce(listener);
signal.remove(listener);
signal.add(listener);
</pre>
<h2>Summary</h2>
<p>Penner argues that since the as3 native event model follows the &#8216;first-wins model&#8217; with respect to priorities, this is the preferred model for handling <code>addOnce</code> and <code>add</code> calls. This argument is a little unsatisfactory, not least because if native as3 design decisions were in-themselves satisfactory, he wouldn&#8217;t have written as3signals in the first place!</p>
<p>My immediate preference was for the &#8216;overwrite model&#8217;, but I can see why people might adopt the &#8216;first-wins model&#8217;. I imagine that there is a relatively even split between the two camps. Therefore, I believe that throwing an error is the least confusing of all possible decisions. If an error is thrown, it is more difficult to write code that has unintended consequences. It forces the inclusion of <code>remove</code> methods, which makes code more readable. It is easy to explain and to document.</p>
<p>Hopefully it is obvious that I have enormous respect Robert Penner and the as3signals project. However, these small design decisions can have a large influence on workflow and they are important to get right. Penner has given the code an <a href="http://osflash.org/">osflash</a> package and he is clearly committed to writing this for the community. I first argued this point very briefly on <a href="http://robertpenner.com/flashblog/2009/09/as3-signals-getting-stronger.html">one of his blog posts on as3signals</a>, but it is an issue that deserved more serious attention. This sort of design decision would be well served by community discussion. If you have an opinion, please comment!</p>
<h2>General Notes on Events</h2>
<p>AS3 signals came out of a discussion on the problems that exist in the current event model. It is difficult to see Adobe deprecate this model any time soon, because their component framework, Cairngorm and the greater Flash/Flex community are now so dependent upon this  model that it is unfeasible to imagine that they would abandon it.</p>
<p>The only way that the signals approach could be adopted <em>en masse</em> is probably if Adobe migrate to it in some future language ASx {x > 3}, or if some major libraries start to adopt it as their event model of choice.</p>
<p>In an earlier post of mine <a href="http://alecmce.com/opinion/as4-thought-experiment">AS4 Thought Experiment</a>, I attempted to think through my preferred API for a future language&#8217;s event model. The article was a response to community chatter about the event model, in part driven by Penner.</p>
<p>We share similar perspectives on how an event model ought to work. On reflection, I prefer Penner&#8217;s implementation with <code>event.add(listener)</code> and <code>event.addOnce(listener)</code> to my proposed <code>event += listener</code>, though I still stand by the argument that ideally, events should be demarcated from elements of an object through their own syntax; in my example by using <code>#event...</code> and by defining them in interface or class through <code>public event drag</code> or <code>public event #drag</code>. This, of course, is <em>never going to happen!</em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/reflecting-on-as3signals/feed</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
	</channel>
</rss>

