ZaaImbue, A dead-simple injection system for Flash

Yesterday in the PushButton Engine IRC channel, we were discussing our need for metadata based injection for the next version of PushButton Engine.

While developing Eden, we encountered a similar problem and ended up writing our own injection system. We’re fond of it, and wanted to use it in PBE… so we open sourced it. Take it, use it, modify it… we’re releasing it under the MIT License.

Check out the source over on GitHub.

Make sure you add this to your compiler arguments:

-keep-as3-metadata+=Inject,PostInject

Here’s a basic example of using ZaaImbue:

package
{
    import com.zaalabs.imbue.IInjector;
    import com.zaalabs.imbue.Injector;

    import flash.display.Sprite;

    public class ImbueExample extends Sprite
    {

        [Inject] 
        // this will inject an instance of ExampleClass into this property
        public var myFirstInjectedInstance:ExampleClass;

        [Inject]
        // this will inject an instance of AnotherExampleClass into this property
        public var mySecondInjectedInstance:AnotherExampleClass;

        public function ImbueExample()
        {
            // create an instance of the classes we want to inject
            var myLocalMember:ExampleClass = new ExampleClass();
            var anotherLocalMember:AnotherExampleClass = new AnotherExampleClass();

            // This is actually all it takes to inject something
            var injector:IInjector = new Injector();
            injector.mapValue(myLocalMember, ExampleClass);
            injector.mapValue(anotherLocalMember, AnotherExampleClass);
            // apply the injections!
            injector.apply(this);
        }

        [PostInject]
        // This gets called after an injection has occurred on the target
        public function onPostInject():void
        {
            trace("We are all done injecting, now we can use our instance!");
            trace("Name of first injected instance:", myFirstInjectedInstance.name);
            trace("Name of second injected instance:", mySecondInjectedInstance.name)
        }

    }
}

Some people have asked us why we called it “Imbue”… frankly… we didn’t want to call it Injection, so we looked up synonyms on the interwebs and imbue was one of them.

We all played a lot of Diablo 2, and had fond memories of Charsi imbuing our gear with magical properties… and that’s where imbue came from.

Tags: , ,

Trackbacks/Pingbacks

  1. Flash Experiements » Blog Archive » Messin’ with PushButtonEngine2 - May 26, 2011

    […] of the engine but so far I am very impressed. This version has a ton of cool features including metadata-based injection, property binding,  and some changes to how PropertyReferences work, which was one of my only […]

Leave a Reply