In a continuation on my series of posts covering the recent Cairngorm 2.2 release, today I’ll give the motivation behind another one of the changes that we made in the MVC micro-architecture for Flex: weak references in the front controller.
In Cairngorm 2.1, the base FrontController class added itself as a listener onto the CairngormEventDispatcher as follows:
CairngormEventDispatcher.getInstance().addEventListener( commandName, executeCommand );
meaning that, when Cairngorm events are dispatched at various places throughout the Flex application, the controller would be notified, and the executeCommand() method called. However, the line of code above added the controller to the CairngormEventDispatcher as a hard reference, meaning that the controller would never be eligible for garbage collection while the CairngormEventDispatcher was still in memory.
Fast forward to the release of Flex 2.0.1 and the addition of Module support to the Flex framework. This feature gives us the ability to load and unload parts of our application, dynamically, at runtime. With Cairngorm 2.1, if someone wanted to create a Cairngorm application as a module, even if that module is unloaded, the controller would never be eligible for garbage collection because the CairngormEventDispatcher (which is a singleton, and therefore global) still has a hard reference onto it.
So, in Cairngorm 2.2, we have made, by default, the addition of the controller to the CairngormEventDispatcher as a weak reference. Holding objects as weak references means that the object will be eligible for garbage collection if the only references to it are weak.
Now, when the FrontController is unloaded, and assuming that all other hard references to it have also been removed, the controller will be eligible for garbage collection, because the CairngormEventDispatcher only has a weak reference onto it.
You can still decided to add the controller as a hard reference to the CairngormEventDispatcher, via a parameter of the addCommand() method of FrontController, but I see little need for that.
There is one final point to add here. The ASDoc for the addCommand() method of FrontController states that the command is added as a weak reference to the controller. That is just plain wrong and I hold my hand up to that – the comments were added in a rush just before I did the final build, instead of when I did the code change. The docs will be fixed in the next release.