The Swiz framework uses a nice approach to inject dependencies into view components. By registering an event listener for the Event.ADDED_TO_STAGE (and the counterpart Event.REMOVED_FROM_STAGE) on the systemManager, they track the adding/removal of view elements at runtime, then introspect the class definition and look out for those magic [Inject] metadata annotations. If found, a dependency from the BeanFactory gets injected (wow, what a rush!)
In cases where you don't want to add Swiz to your application (yes, I admit it happened to me when I created a little POC) you can use the same approach to inject certain "global" dependencies (Models being a good example) into your views to avoid the Singleton anti-pattern.
Implementation is pretty straighforward. In my case I have a central Model class which holds references to certain other objects. This model gets instantiated just once in the main Flex application file. Now, in each MXML view that should access this Model object, I created a new public var model of type Model (in Swiz we would now have to put [Inject] on top of it but we don't do this here, it's just convention over configuration).
The last bit of "wiring" is to use the creationComplete Event of the main application file to an event listener for the Event.ADDED_TO_STAGE event to the systemManager. The event handler function then looks like this (ok, not pretty and it works 100% in my use case):
private function addedToStageHandler(event:Event):void
const target:Object = event.target;
// check if the target has a model property
// and if so, check if it's not set yet
// (no further type checking here so beware!!)
if (target != this && target.hasOwnProperty("model") && target.model !== model)
// inject the model
target.model = model;
Disclaimer: of course, I don't want you to stop using Swiz in favour of this (probably silly) approach. I still use Swiz all the time - except for the little POC :) So, if you want to try it go ahead, if you need more, please take a look at Swiz or one of the other fine DI frameworks for AS3/Flex!
There are no comments for this entry.