0.2.0 • Published 8 years ago
jscomponent v0.2.0
JS Component
This is the implementation of a Dependency Injection system.
Style your code with components, providers and modules.
Providers are initialized and cached in the module, before they are injected in other objects
Inspired by Angular, made for Node.js
Example:
const { Module, Provider, Component, bootstrap } = require("jscomponent");
// Create a provider
class Service {
sayHi() {
console.log("Hello world!");
}
}
Provider(Service);
// Create a component
class AppComponent {
constructor() {
this.service.sayHi();
}
}
Component(AppComponent, { service: Service });
// Create a module. It initializes and injects the providers
class AppModule {}
Module(AppModule, {
providers: [Service],
components: [AppComponent]
});
bootstrap(); // This will actually instantiates all the modules
new AppComponent(); // It will prints 'Hello world!'
API
Module(object, config)
Description: decorate your module object, with the providers and components to inject
Params:
{object} object
{hashMap} config
Config can have the following properties:
config | type |
---|---|
providers | Array |
components | Array |
Component(object, providersMap)
Description: decorate the object with the providers to inject.
The injected providers will be available in the instance of the object (directly in the constructor).
Params:
{object} object
{hashMap} ProvidersMap = Keys are the variables names, which to access the providers from the instance. Example: {"app": AppProvider}
Provider(object, providersMap)
Description: decorate the object with the providers to inject.
The injected providers will be available in the instance (when the onInit() hook has been called, NOT in the constructor, see the example below).
Params:
{object} object
{hashMap} ProvidersMap = Keys are the variables names, which to access the providers from the instance. Example: {"app": AppProvider}
onInit() hook for providers
Modules will call the providers onInit() method, after the complete initialization of a module. Injected providers are available only from there, not in the constructor.
This also lets injecting a provider into another provider, or to allow e.g. circular dependency reference.
Example:
class Provider1 {}
Provider(Provider1);
class Provider2 {
constructor() {} // provider1 is not available here
onInit() {
console.log("onInit called");
}
}
Provider(Provider2, { provider1: Provider1 });
class AppModule {}
Module(AppModule, {
providers: [Provider1, Provider2]
});
bootstrap();
bootstrap()
Description: call it after you defined all the modules (and before of the components initialization).
This method will initialize the modules and their providers
Tests
npm test
License
MIT