Konoha
Konoha is Dependency Injection Container that allows you take the advantage of the dependency injection principle in Javascript.
Installation
npm install --save konoha
Getting Started
First we need to create a new instace of Konoha. After that we can use methods like set
and get
to access it.
Using ES6
; { super; this; this; this; this; ... }
Pre-ES6 (NodeJS or CommonJS)
var Konoha = ;var app = ; // you can chain any of the API methodsapp ; app;
API
get(name)
Gets the value by the name.
app;app; app; // falseapp; // 'bar'
set(name, value)
Sets a new attribute with given value.
You can set anything on the value. If the value is a function it will only be constructed/called once but it won't called until it is requested by get
.
The function context will be the app
, so you access to the app
if you need it.
This shouldn't be used for setting/binding class definitions. Only the class intances should be stored.
app;app; // sets an API serviceapp;app; var isValid = app;var user = app; // get API service// This will initiate a new instance of the APIvar api = app;api; // This time it will use existing API instance, since the function only gets called oncevar api = app;
has(name)
Checks if there is anything registered under given name.
app; // false app; app; // true
keys()
Get all the registered names as an array.
app;app; app; // ['version', 'isValid']
raw(name)
Returns the original definition of the service.
app; var api = app; // the callback/function definition
extend(name, callback)
Allows you to extend/modify the registered service
Let's add a response handler to the API service that converts the response to JSON. To do that we need to pass a function that takes one argument which will be the current value of the existing service. It should return a new value that will replace the existing value.
app; app;
Now every response you get should be converted into JSON.
factory(name, service)
Not everytime you want to get the cached (constructed) service. Use factory
to create a service
that will be reconstructed/called everytime it gets requested by get
.
app; // Creates new Person instancevar person1 = app; // Creates new Person instance againvar person2 = app;
protect(name, value)
Unlike set
or factory
which always returns the value of the service/function
the protect
allows you define a service/function that will never called by get
.
It's something that is needed if you want to store something without getting modified by get
.
The protect
will always return the definition of the service/function.
app; app; // will return the function that takes a name argument var siri = app'Siri';console; // 'Siri' var alexa = app'Alexa';console; // 'Alexa'
register(provider)
This function allows you to register services in bulk. The provider
function that is passed
doesn't become a service. But it gets called immediately.
app;