Dependency Injection Module
The module was inspired by di.js in @angular.
- Decorator
- Global Variables
- Functions
- Interface
- componentConfig (reference only)
- providerConfig (reference only)
- Examples
- Lisence
Use @Injectable()
decorator to register class to INJECTABLE_STORE
Otherwise the class cannot be instanized by function instanize
Use @Inject(...Providers)
decorator to inject providers(functions) to class.
The inputed providers will be used to construct instance of decorated class.
NOTE: the sequence of providers is NOT restricted
Use @Component(config: componentConfig)
to decorate class.
pass componentConfig to decorator to determine the specific providers for constructing class instance.
Example: bootstrap({ provider: [...Function] });
This is where intanizing started.
The instanzing function will generate instaces of inputed Providers and store them to INSTANCE_STORE
as global instance.
The function returns an instance which all dependencies has been injected.
The function returns an instance of registered injectable class.
{
restrict?: boolean,
provider: [Function|providerConfig]
}
NOTE: In restrict mode, if the dependency instance cannot be found, it will throw an Error. Otherwise it will return null
{
provider: Function,
useValue?: any,
useClass?: Function,
useExistInstance?: any
}
The priority is useClass > useValue > useExistInstance
The index.web.js has exposed a global variable DI
, use <script> tag to import index.web.js
<html>
<head></head>
<body>
<script src="path/to/your/index.web.js"></script>
<script src="your/own/js/my.js"></script>
</body>
</html>
@Injectable()
class Wheel {
showInfo(){ console.log('Wheel module is working OK...') };
}
@Injectable()
class Engine {
showInfo(){ console.log('Engine module is working OK...') };
}
@Injectable()
class V12Engine {
showInfo(){ console.log('V12 Engine starts!') }
}
@Component({
provider: [
{ provider: Engine, useClass: V12Engine }
]
})
class Car {
constructor( private wheel: Wheel, private engine: V12Engine ) {
this.wheel.showInfo();
this.engine.showInfo();
}
}
boostrap({
provider: [
Wheel,
Engine,
V12Engine
]
});
var car = new Car( new Wheel(), new Engine() );
var racingCar = constrct(Car);
Wheel module is working OK...
Engine module is working OK...
Wheel module is working OK...
V12 Engine starts!