Skip to content

Injection

Tony Findeisen edited this page Jun 23, 2012 · 7 revisions

Injection

Injection is a powerful feature where you require objects from a specified type and get them. This allows to work with different implementations for the browser, node or in test caces and replaces the static methods MyClass.createInstance(), because those wouldn't work on node*.

Injection is currently available only for Components and must be declared inside your application. External injection will be available soon.

Setup injection in your application

<js:Application xmlns:js="js.core" xmlns:conf="js.conf">
    <js:Injection>
         <js:I18n locale="en_EN" />
         <conf:Configuration type="js.data.LocalStorageDataSource" singleton="true" />
    </js:Injection>
</js:Application>

This creates a new instances of I18n and adds it to the injection container. Also a configuration is added which configures the injection container to allow the creation of js.data.LocalStorageDataSource if no instance from requested type is available.

Adding named instances

A named instances can be added at runtime using the following code.

var myInstance = new MyClass();
this.$stage.$injection.addInstance("globalName", myInstance);

Require injection

A requirement for injection can be defined in each component with the inject definition. The definition is a Object taking the name under which the injected object will be available as key and the requested type as value. The requested type can either be a String for named instances or a factory.

The following example shows how a DataSource and a named instance will be injected:

define(['js/core/Module', 'js/data/DataSource'], function(Module, DataSource) {

    return Module.inherit({

        inject: {
             api: DataSource,    // will inject the LocalStorageDataSource as this.$.api
             foo: "globalName"   // will inject the manually added MyInstance as this.$.foo
        },

        initialize: function() {
              console.log([this.$.api, this.$.foo]);
        }

    });

});

* Of cause would static methods work on node, but these class methods are shared by all application instances rendered parallel on node.

Clone this wiki locally