<?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>Richard Lord &#187; Free code</title>
	<atom:link href="http://www.richardlord.net/blog/tag/free-code/feed" rel="self" type="application/rss+xml" />
	<link>http://www.richardlord.net</link>
	<description>Actionscript/Flex, PHP and Java developer</description>
	<lastBuildDate>Mon, 23 Jan 2012 17:07:46 +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>Object Pool class</title>
		<link>http://www.richardlord.net/blog/object-pool-class</link>
		<comments>http://www.richardlord.net/blog/object-pool-class#comments</comments>
		<pubDate>Wed, 08 Oct 2008 13:50:51 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Free code]]></category>
		<category><![CDATA[Object pool]]></category>

		<guid isPermaLink="false">http://www.bigroom.co.uk/blog/object-pool-class/</guid>
		<description><![CDATA[<p>Two of the slow operations in the flash player are object creation and garbage collection. If we pool objects - save objects when they're no longer needed and reuse them later when another object of the same type is required - then object creation is kept to a minimum and garbage collection is reduced to zero...</p>]]></description>
			<content:encoded><![CDATA[<p>Two of the slow operations in the flash player are object creation and garbage collection. If we pool objects &#8211; save objects when they&#8217;re no longer needed and reuse them later when another object of the same type is required &#8211; then object creation is kept to a minimum and garbage collection is reduced to zero.</p>

<p><a href="http://blog.joa-ebert.com/">Joa Ebert</a> discussed this in his presentation at <a href="http://www.flashonthebeach.com/">Flash on the Beach</a>. I already use specific object pooling in <a href="http://flintparticles.org/">Flint particles</a>, but while Joa was talking I had an idea and wrote a class for generic object pooling of all object types. I finally had time to test the class, and it works as expected, so I&#8217;ve added it to my <a href="https://github.com/richardlord/Actionscript-Toolkit/blob/master/src/net/richardlord/utils/ObjectPool.as">open code repository</a>.</p>

<p>The object pool class manages pooling of all objects through two simple methods. You can obtain an object from it like this</p>

<pre class="code">var obj:SomeClass = ObjectPool.getObject( SomeClass );</pre>

<p>If there are any such objects in the pool, one of them will be returned. If there are no such objects in the pool, a new one will be created and returned to you.</p>

<p>When you no longer need an object, you can add it to the pool for later reuse like this</p>

<pre class="code">ObjectPool.disposeObject( obj );</pre>

<p>The object doesn&#8217;t have to have been created through the pool &#8211; any object can be dropped into the pool with the disposeObject method.</p>

<p>The source code is available in <a href="https://github.com/richardlord/Actionscript-Toolkit/blob/master/src/net/richardlord/utils/ObjectPool.as">my GitHub code repository</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/object-pool-class/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Actionscript 3 tetris source code</title>
		<link>http://www.richardlord.net/blog/actionscript-3-tetris-source-code</link>
		<comments>http://www.richardlord.net/blog/actionscript-3-tetris-source-code#comments</comments>
		<pubDate>Thu, 13 Dec 2007 11:35:13 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Free code]]></category>
		<category><![CDATA[Game development]]></category>
		<category><![CDATA[Tetris]]></category>

		<guid isPermaLink="false">http://www.bigroom.co.uk/blog/actionscript-3-tetris-source-code/</guid>
		<description><![CDATA[This will certainly be useful to anyone wanting to make a tetris game. It's probably also useful to anyone learning Actionscript 3, particularly if they want to make games.

The <a href="http://flashgamecode.net/free/tetris-engine">source code</a> is on the <a href="http://flashgamecode.net/">Flash Game Code</a> web site. It's in two parts - an engine, which does the game part, and a sample game that uses the engine. Have fun.]]></description>
			<content:encoded><![CDATA[<p>This will certainly be useful to anyone wanting to make a tetris game. It&#8217;s probably also useful to anyone learning Actionscript 3, particularly if they want to make games.</p>

<p><b><a href="/files/TetrisGameEngine.zip">Download the source code</a></b></p>

<p>The source code is in two parts &#8211; an engine, which does the game part, and a sample game that uses the engine. Have fun.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/actionscript-3-tetris-source-code/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Radial Perlin Noise</title>
		<link>http://www.richardlord.net/blog/radial-perlin-noise</link>
		<comments>http://www.richardlord.net/blog/radial-perlin-noise#comments</comments>
		<pubDate>Mon, 29 Oct 2007 14:00:34 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Free code]]></category>
		<category><![CDATA[Perlin noise]]></category>

		<guid isPermaLink="false">http://www.bigroom.co.uk/blog/radial-perlin-noise/</guid>
		<description><![CDATA[<p>I was messing around with perlin noise, creating a radial effect for a game I'm working on. The result is a RadialPerlin class for creating radial perlin noise bitmaps. The code is licenced under the MIT license. Have fun, and if you make something interesting with it let me know.</p>]]></description>
			<content:encoded><![CDATA[<p>I have been messing around with perlin noise, creating a radial effect for a game I&#8217;m working on. The result is a RadialPerlin class for creating radial perlin noise bitmaps like this.</p><br />

<div class="spaced"><div id="swf4f2e9ac90aa54">
<p><b>Flash required:</b> You need version 10 or later of the free Flash player from Adobe to use this content. To download and install the free player from Adobe's web site <a href="http://get.adobe.com/flashplayer/">click here</a>.</p>
</div>
<script type="text/javascript">
var params = {loop:"false",quality:"high",allowfullscreen:"true"};
var flashvars = {};
swfobject.embedSWF("/images/blog/RadialPerlinDemo.swf", "swf4f2e9ac90aa54", "200", "200", "10.0.0", "/swf/expressInstall.swf", flashvars, params, {} );
</script></div>

<p>The code is in a single class called RadialPerlin, used like this</p>

<pre class="code">var perlin:RadialPerlin = new RadialPerlin( 100, 3, 
        Math.random() * 100000, false, 15, false, true );
perlin.draw( 0, 0 );
var bmp:Bitmap = new Bitmap( perlin.bitmapData );
addChild( bmp );</pre>

<p><a href="http://bigroom.googlecode.com/files/RadialPerlin.zip" title="Download source code">
<img src="/images/icons/asfile.gif" width="31" height="31" alt="Download source code" class="icon" />
<b>Download the RadialPerlin class and demo.</b></a></p>

<p>The RadialPerlin object is initialised with some values (details of the parameters are in the class file) then drawn into a BitmapData object using its draw method. The draw method takes a couple of offset parameters &#8211; one for the distance from the centre and the other for the rotation. You can then grab the BitmapData  object from the RadialPerlin object via its bitmapData property and do what you like with it.</p>

<p>The code is licenced under the MIT license. Have fun, and if you make something interesting with it let me know.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/radial-perlin-noise/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>PHP Password Security</title>
		<link>http://www.richardlord.net/blog/php-password-security</link>
		<comments>http://www.richardlord.net/blog/php-password-security#comments</comments>
		<pubDate>Wed, 10 Oct 2007 15:45:34 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Best practice]]></category>
		<category><![CDATA[Free code]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://www.bigroom.co.uk/blog/php-password-security/</guid>
		<description><![CDATA[<p>If you build websites that require users to register it's your responsibility to keep their passwords safe. And if you're storing the passwords in plain text then you're not doing your job properly. What happens if your database is stolen? It's not just your site that is compromised. Since most users use the same password on multiple sites, all those sites have also been compromised...</p>]]></description>
			<content:encoded><![CDATA[<p>If you build websites that require users to register it&#8217;s your responsibility to keep their passwords safe. And if you&#8217;re storing the passwords in plain text then you&#8217;re not doing your job properly. It may be that, <a href="http://reddit.com/info/usqe/comments/cuugl">like Reddit</a>, you think that storing passwords in plain text leads to a better user experience. I happen to agree with you. But then, like Reddit, what happens if your database is stolen? It&#8217;s not just your site that is compromised. Since most users use the same password on multiple sites, all those sites have also been compromised.</p>

<p>No data is entirely secure, and if anyone else has access to your webserver (the company managing the server for you?) or your database (the company storing the backups?) then you don&#8217;t have total control over the security anyway. So there&#8217;s always a chance your database could be stolen. So, the simple rule is to hash your passwords.</p>

<h3>Hashing</h3>

<p>A hash is a string derived from the original password via a one-way algorithm. In other words, it&#8217;s easy to create the hash from the original, but harder (when used for security, ideally impossible) to create the original from the hash. You store the hash in the database, and when the user signs-in you hash the password they sign-in with and compare it to the hash in the database. Something like this</p>

<pre class="code">if( $user->passwordhash == sha1( $_POST['password'] ) )</pre>

<p>That way, you never store the user&#8217;s password.</p>

<p>There are a number of hashing algorithms in PHP, of which md5 and sha1 are the most commonly used. Unfortunately, neither is as secure as they were once thought to be. It would be better to use a more secure hash, and if you have the Hash engine in your PHP installation (included by default since PHP 5.1.2) then you have access to many more algorithms. So a better example would be</p>

<pre class="code">if( $user->passwordhash == hash( 'whirlpool', $_POST['password'] ) )</pre>

<h3>Rainbow tables</h3>

<p>But there&#8217;s another problem. Once your database is stolen, the thief has plenty of time to crack the passwords using a simple <a href="http://www.codinghorror.com/blog/archives/000949.html">Rainbow Table attack</a>. This involves creating a large selection of hashes based on likely passwords (e.g. every word in the dictionary) and then comparing the hashes with the hashes in your database. Within an hour or so, half the passwords in your database will probably have been cracked.</p>

<p>To prevent this you should salt each password by adding a random string to it (called a salt or nonce). The time consuming part of a rainbow table attack is building the dictionary of hashes. Adding a random salt to the password means the thief has to build a whole new dictionary of hashes for each salt, making a rainbow table attack too time consuming to be viable. Each password should have a different salt, and the salt doesn&#8217;t even need to be secret.</p>

<h3>The Code bit</h3>

<p>So, for secure passwords you need code that looks something like this</p>

<pre class="code">// get a new salt - 8 hexadecimal characters long
// current PHP installations should not exceed 8 characters
// on dechex( mt_rand() )
// but we future proof it anyway with substr()
function getPasswordSalt()
{
    return substr( str_pad( dechex( mt_rand() ), 8, '0',
                                           STR_PAD_LEFT ), -8 );
}

// calculate the hash from a salt and a password
function getPasswordHash( $salt, $password )
{
    return $salt . ( hash( 'whirlpool', $salt . $password ) );
}

// compare a password to a hash
function comparePassword( $password, $hash )
{
    $salt = substr( $hash, 0, 8 );
    return $hash == getPasswordHash( $salt, $password );
}

// get a new hash for a password
$hash = getPasswordHash( getPasswordSalt(), $password );</pre>

<p>You don&#8217;t have to attach the salt to the hash, you can instead store them separately within the database, but I like keeping them together in a single string. Equally, the salt needn&#8217;t be in hexadecimal, but I like the symmetry with the hexadecimal hash.</p>

<p>Finally, <a href="http://www.matasano.com/log/958/enough-with-the-rainbow-tables-what-you-need-to-know-about-secure-password-schemes/">as Thomas Ptacek points out</a>, you don&#8217;t want the fastest hash algorithm in the world for this &#8211; a fast algorithm is more useful to an attacker than it is to you.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/php-password-security/feed</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Keyboard polling class &#8211; bug fix</title>
		<link>http://www.richardlord.net/blog/keyboard-polling-class-bug-fix</link>
		<comments>http://www.richardlord.net/blog/keyboard-polling-class-bug-fix#comments</comments>
		<pubDate>Tue, 04 Sep 2007 07:53:07 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Free code]]></category>
		<category><![CDATA[Game development]]></category>
		<category><![CDATA[Keyboard polling]]></category>

		<guid isPermaLink="false">http://www.bigroom.co.uk/blog/keyboard-polling-class-bug-fix/</guid>
		<description><![CDATA[There was an error in the Keyboard polling class that I posted yesterday. If you downloaded the class you&#8217;ll want the new version, which is available here.]]></description>
			<content:encoded><![CDATA[<p>There was an error in the Keyboard polling class that I <a href="/blog/polling-the-keyboard-in-actionscript-3">posted yesterday</a>. If you downloaded the class you&#8217;ll want the new version, <a href="https://github.com/richardlord/Actionscript-Toolkit/blob/master/src/net/richardlord/input/KeyPoll.as">which is available here</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/keyboard-polling-class-bug-fix/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Polling the keyboard in Actionscript 3</title>
		<link>http://www.richardlord.net/blog/polling-the-keyboard-in-actionscript-3</link>
		<comments>http://www.richardlord.net/blog/polling-the-keyboard-in-actionscript-3#comments</comments>
		<pubDate>Mon, 03 Sep 2007 17:36:35 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Free code]]></category>
		<category><![CDATA[Game development]]></category>
		<category><![CDATA[Keyboard polling]]></category>

		<guid isPermaLink="false">http://www.bigroom.co.uk/blog/polling-the-keyboard-in-actionscript-3/</guid>
		<description><![CDATA[<p>Games often need to get the current state of various keys in order to respond to user input. This is not the same as responding to key down and key up events, but is rather a case of discovering if a particular key is currently pressed.</p>

<p>In Actionscript 2 this was a simple matter of calling Key.isDown() with the appropriate key code. But in Actionscript 3 Key.isDown no longer exists and the only intrinsic way to react to the keyboard is via the key up and key down events. To rectify this I created the KeyPoll class...</p>]]></description>
			<content:encoded><![CDATA[<p>Games often need to get the current state of various keys in order to respond to user input. This is not the same as responding to key down and key up events, but is rather a case of discovering if a particular key is currently pressed.</p>

<p>In Actionscript 2 this was a simple matter of calling Key.isDown() with the appropriate key code. But in Actionscript 3 Key.isDown no longer exists and the only intrinsic way to react to the keyboard is via the key up and key down events.</p>

<p>To rectify this I created the KeyPoll class, which has isDown and isUp methods, each taking a key code as a parameter and returning a Boolean. The class is <a href="https://github.com/richardlord/Actionscript-Toolkit/blob/master/src/net/richardlord/input/KeyPoll.as">in my GitHub code repository</a>.</p>

<p>Using the class looks like this</p>

<pre class="code">package
{
  import flash.display.Sprite;
  import flash.events.Event;
  import flash.ui.Keyboard;
  import net.richardlord.input.KeyPoll;

  public class Test extends Sprite {
    var key:KeyPoll;

    public function Test() {
      key = new KeyPoll( this.stage );
      addEventListener( Event.ENTER_FRAME, enterFrame );
    }

    public function enterFrame( ev:Event ):void {
      if( key.isDown( Keyboard.LEFT ) ) {
        trace( "left down" );
      }
      if( key.isDown( Keyboard.RIGHT ) ) {
        trace( "right down" );
      }
    }
  }
}</pre>

<p>The constructor for the KeyPoll class takes a single parameter which is a DisplayObject on which the KeyPoll object should listen to keyboard events. To listen globally to all keyboard input this should be the stage, as in the example.</p>

<p>The class uses a ByteArray to hold the current keyboard state, which is updated in response to Keyboard events and queried by the public methods, isDown and isUp. Using a ByteArray is more compact than using an Array of Booleans, and in tests it also turned out to be marginally faster, although the difference in speed was not significant enough to matter.</p>

<p>Further, the class clears the key state array when the deactivate event occurs, so key state is not retained if the Flash Player loses focus and stops receiving keyboard input.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/polling-the-keyboard-in-actionscript-3/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Events in Actionscript 3</title>
		<link>http://www.richardlord.net/blog/events-in-actionscript-3</link>
		<comments>http://www.richardlord.net/blog/events-in-actionscript-3#comments</comments>
		<pubDate>Wed, 15 Aug 2007 14:12:38 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Free code]]></category>

		<guid isPermaLink="false">http://www.bigroom.co.uk/blog/events-in-actionscript-3/</guid>
		<description><![CDATA[<p>There was lots of positive feedback to <a href="/blog/events-in-actionscript-2/">yesterday's post</a> about my Actionscript 2 event class, so I decided to create an Actionscript 3 version. I added a lot of features while I was at it - listener priorities, preventDefault, stopNotification (aka stopImmediatePropagation), hasListeners, weak references, and to send the event as the single parameter when notifying listeners...</p>]]></description>
			<content:encoded><![CDATA[<p>There was lots of positive feedback to <a href="/blog/events-in-actionscript-2">yesterday&#8217;s post</a> about my Actionscript 2 event class, so I decided to create an Actionscript 3 version. I added a lot of features while I was at it &#8211; listener priorities, preventDefault, stopNotification (aka stopImmediatePropagation), hasListeners, weak references, and to send the event as the single parameter when notifying listeners.</p>

<p>Basically it implements almost all the features in the Actionscript 3 event model, but with all the functionallity contained within the event class itself. This way events are identified as properties of the object rather than by Strings (or by static properties containing those strings).</p>

<p>A simple example of its use would be this clicked event</p>

<pre class="code">package
{
   import bigroom.BrEvent;
   import flash.display.*;
   import flash.events.MouseEvent;
   
   class Listenable extends Sprite
   {
      public var clicked:BrEvent;
      
      public function Listenable() {
         clicked = new BrEvent( this );
         graphics.beginFill( 0xFF0000 );
         graphics.drawCircle( 50, 50, 50 );
         addEventListener( MouseEvent.MOUSE_DOWN, mouseListener );
      }
      
      public function mouseListener( ev:MouseEvent ):void {
         clicked.notify();
      }
   }
}</pre>

<pre class="code">package
{
   import flash.display.*;
   
   public class Test extends Sprite
   {
      public function Test() {
         var listen:Listenable = new Listenable();
         addChild( listen );
         listen.clicked.addListener( doClick );
      }
      
      public function doClick( ev:BrEvent ):void {
         trace( "clicked" );
      }
   }
}</pre>

<p><a href="/files/BrEvent.zip" title="Download source code">
<img src="/images/icons/asfile.gif" width="31" height="31" alt="Download source code" class="icon" />
<b>Download the BrEvent classes.</b></a></p>

<p>I first tried to implement this using entirely custom code, and everything worked fine except the weak references. I used the <a href="http://www.bigroom.co.uk/blog/create-your-own-weak-references-in-actionscript-3">weak references as described in this post</a>, and came across <a href="http://www.bigroom.co.uk/blog/different-types-of-weak-references">the problem described here</a>. This implementation is BrEvent1 in the download. It&#8217;s great if you don&#8217;t use the weak references, and interesting anyway.</p>

<p>So then I implemented it utilising the existing Event and EventDispatcher classes and that works fine. This implementation is BrEvent2 in the download. There&#8217;s a couple of redundant methods calling methods in the super class but they&#8217;re there to make the point about the overriden methods.</p>

<p>The one feature of the Actionscript 3 event model this class doesn&#8217;t implement is the capture and bubbling phases of events on display objects. The reason is, it&#8217;s not clear what events should be called in the various display objects up the chain. Unless I somehow hack the chosen events into the DisplayObject class itself, the events will only exists on selected display objects. So I didn&#8217;t implement this.</p>

<p>Having done this, I still don&#8217;t expect to use it. Although I prefer it to the built-in event handling in Actionscript 3, the built in event handling is good enough so I will use that for consistency.</p>

<p>So it was really just a short learning experience. It didn&#8217;t take long and I got to play meaninglessly with Actionscript for a morning. If you have any suggestions or you find the class(es) useful, let me know below.</p>

<p>Also, if you can think of a better name, let me know that too. I wanted to simply call the class Event but that would be too confusing with the built-in Event class.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/events-in-actionscript-3/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Different types of weak references</title>
		<link>http://www.richardlord.net/blog/different-types-of-weak-references</link>
		<comments>http://www.richardlord.net/blog/different-types-of-weak-references#comments</comments>
		<pubDate>Wed, 15 Aug 2007 13:33:53 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Free code]]></category>
		<category><![CDATA[Weak reference]]></category>

		<guid isPermaLink="false">http://www.bigroom.co.uk/blog/different-types-of-weak-references/</guid>
		<description><![CDATA[<p>Actionscript 3 seems to have two different types of weak references. The difference relates to method closures (or bound methods) and the weak references used by the EventDispatcher and Dictionary classes. Try the following...</p>]]></description>
			<content:encoded><![CDATA[<p>Actionscript 3 seems to have two different types of weak references. The difference relates to method closures (or bound methods) and the weak references used by the EventDispatcher and Dictionary classes. Try the following</p>

<pre class="code">package
{
   import flash.display.*;
   import flash.utils.Dictionary;
   import flash.events.MouseEvent;
   
   public class Test extends Sprite
   {
      private var dic:Dictionary;
      private var store:Function;
      
      public function Test() {
         var listen:Sprite = new Sprite();
         listen.graphics.beginFill( 0xFF0000 );
         listen.graphics.drawCircle( 50, 50, 50 );
         addChild( listen );

         dic = new Dictionary( true );
         dic[inDictionary] = 1;
         dic[inDictionaryAndProperty] = 1;
         store = inDictionaryAndProperty;
         
         listen.addEventListener( MouseEvent.CLICK, doClick );
         listen.addEventListener( MouseEvent.CLICK, 
                             inEventListeners, false, 0, true );
      }
        
      public function doClick( ev:MouseEvent ):void {
         for( var fn:Object in dic ) {
            fn( ev );
         }
      }

      public function inDictionary( ev:MouseEvent ):void {
         trace( "method in dictionary" );
      }

      public function inDictionaryAndProperty( ev:MouseEvent ):void {
         trace( "method in dictionary and property" );
      }
        
      public function inEventListeners( ev:MouseEvent ):void {
         trace( "method in event listeners" );
      }
   }
}</pre>

<p>The output is</p>

<pre class="code">method in dictionary and property
method in event listeners</pre>

<p>The EventDispatcher retains the weak reference to the method closure (inEventListeners) because the object it&#8217;s bound to still exists. It will drop its reference to the method closure when the bound object no longer exists.</p>

<p>The Dictionary, however, doesn&#8217;t retain the weak reference to the method closure (inDictionary), despite the fact that the method still exists (it exists in the class) and the object it is bound to still exists.</p>

<p>If, however, you have another, strong, reference to the same method closure (inDictionaryAndProperty), then it isn&#8217;t garbage collected and the Dictionary retains its reference to it.</p>

<p>So the EventDispatcher and Dictionary treat weak references to method closures differently.</p>

<p>It seems to me that the Dictionary takes a purist view &#8211; it holds the only reference to the method closure so it can be garbage collected &#8211; while the EventDispatcher takes a practical view &#8211; the method and the bound object both exist so the method closure should be retained.</p>

<p>Why the difference? I&#8217;d love to know.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/different-types-of-weak-references/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating weak references in Actionscript 3</title>
		<link>http://www.richardlord.net/blog/create-your-own-weak-references-in-actionscript-3</link>
		<comments>http://www.richardlord.net/blog/create-your-own-weak-references-in-actionscript-3#comments</comments>
		<pubDate>Wed, 15 Aug 2007 10:07:17 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Free code]]></category>
		<category><![CDATA[Weak reference]]></category>

		<guid isPermaLink="false">http://www.bigroom.co.uk/blog/create-your-own-weak-references-in-actionscript-3/</guid>
		<description><![CDATA[<p>A weak reference is a reference that does not prevent the object from being garbage collected. It's great that Actionscript 3 has weak references in the EventDispatcher and Dictionary classes. But sometimes you want to create your own weak references. The source code is very short...</p>
]]></description>
			<content:encoded><![CDATA[<p>A weak reference is a reference that does not prevent the object from being garbage collected. It&#8217;s great that Actionscript 3 has weak references in the EventDispatcher and Dictionary classes. But sometimes you want to create your own weak references. Something along the lines of</p>

<pre class="code">var weak:WeakRef = new WeakRef( someObject );</pre>

<p>Well, there is a way. It&#8217;s a bit of a hack, and unfortunately uses a full Dictionary object for each weak reference, but it works. The source code is on <a href="https://github.com/richardlord/Actionscript-Toolkit/blob/master/src/net/richardlord/utils/WeakRef.as">my public GitHub repository</a>.</p>

<p>To use the class</p>

<pre class="code">// Create a weak reference
var weak:Weakref = new WeakRef( obj );

// Later use the referenced object
var strong = weak.get();
if( strong != null )
{
    // use strong here
}
else
{
    // garbage collector has disposed of the object
}</pre>

<p>If the get method returns null then the object has been garbage collected.</p>

<p>The source is free under the terms of the MIT licence.</p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/create-your-own-weak-references-in-actionscript-3/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Events in Actionscript 2</title>
		<link>http://www.richardlord.net/blog/events-in-actionscript-2</link>
		<comments>http://www.richardlord.net/blog/events-in-actionscript-2#comments</comments>
		<pubDate>Tue, 14 Aug 2007 13:27:49 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[All]]></category>
		<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Free code]]></category>

		<guid isPermaLink="false">http://www.bigroom.co.uk/blog/events-in-actionscript-2/</guid>
		<description><![CDATA[<p>I documented my technique for implementing event dispatching <a href="http://flashgamecode.net/free/event-class">over on the Flash Game Code site</a>. I've been using this method for a couple of years now and I think it's a lot better than EventDispatcher or ASBroadcaster. <a href="http://flashgamecode.net/free/event-class">Take a look if your interested</a>. Comments are welcome below. The source code is available for free on flashgamecode.net under the MIT licence.</p>]]></description>
			<content:encoded><![CDATA[<p>Macromedia adopted two techniques for implementing event listeners. They are the ASBroadcaster class, 
used in Flash&#8217;s intrinsic classes, and EventBroadcaster, used in all their components. I dislike both 
these techniques for a number of reasons.</p>

<ul>
<li>Both are mixins, with all the disadvantages that entails.</li>
<li>Both require the listening object to define functions with specific names in order to handle the events.</li>
<li>With ASBroadcaster, all events are broadcast to all listeners. There is no way for the listener to select only specific events to listen too.</li>
<li>With EventDispatcher, events must be specified by name as a String, which means there is no compile time checking that the event exists.</li>
</ul>

<p>So a couple of years ago I devised a new option. This technique uses a single Event class. You set-up events
on an object by creating a public property that is an Event. Other objects may then listen to this event and the
object dispatches the event when it wishes. For example</p>

<p class="code">import BigRoom.Event;

class SimpleButton
{
    public var click:Event;
	
    public function SimpleButton()
    {
        click = new Event();
    }
    
    public function onRelease():Void
    {
        click.notify( this );
    }
}</p>

<p>The notify call dispatches the event to all the listeners along with any parameters passed to the notify 
method. Listeners subscribe to the event via a call to the addListener method of the event, as in the 
following example</p>

<p class="code">class ButtonListener
{
    public function ButtonListener( btn:SimpleButton )
    {
        btn.click.addlistener( this, buttonClick );
    }
    
    public function buttonClick( obj:SimpleButton ):Void
    {
        // do something here&#8230;
    }
}</p>

<p>No mixins, no Strings, no fixed method names, and listeners subscribe to receive specific events. The
technique isn&#8217;t without its flaws, but I consider it far better than ASBroadcaster or EventDispatcher.</p>

<p><a href="/files/BigRoom_Event.zip" title="Download source code">
<img src="/images/icons/asfile.gif" width="31" height="31" alt="Download source code" class="icon" />
<b>Download the Event class.</b></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.richardlord.net/blog/events-in-actionscript-2/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

