DI-JS
DI-JS is a simple Dependency Injection for JavaScript for the Web. Unlike ES6's module, this is written to work with HTML Imports and libraries not using ES6 module.
One of the main features of DI-JS is the ability for the developer to override any bindings. This makes testing and writing customizable frameworks easier.
Installation
npm install --save-dev di-js
To use this, include this in your html file:
Basic Usage
There are two main usages of DI-JS: Injecting and Binding
Injecting
Use the DIJS.run
method to inject values. For example:
DIJS;
In the example above, the function receives two functions:
require
injects the given key. In this case, it injectsservice.iceCream
andglobal.URL
optional
optionally injects theservice.config
. If this value is not bound, it will return anundefined
.
This function is called a "provider".
Binding
DI-JS supports two kinds of bindings: Global and Local bindings. Global bindings are done using the
DIJS.bind
method:
DIJS ;
The first argument to DIJS.bind
is the key to bind the value to. The second argument is a
provider to run. Note that this function returns a Service. This is the value that will be bound to
service.iceCream
.
The second type of binding is local binding. This can be done using the DIJS.with
method:
DIJS ;
Calling with
returns a child scope with the given value bound. The value bound by the with
method will only be available to descendants of that scope.
Another way to locally bind a value is using constant
. This is just a shortcut to:
DIJS;
Running a program
Note that DI-JS lazily evaluates any providers. Calling DIJS.bind
does not run the provider. The
only time a provider is run is during injection or when calling DIJS.run
:
DIJS;
DIJS.run
is the entry point of an application. Every code that depends on a bound value must run
inside a provider. This ensures that the value is ready when it is used.
Calling run also creates a new "run context". A given run context will have its own bindings, even the global bindings. No bindings will be shared between two different run context. This will help to keep the global environment clean for testing.
Overriding values
One of the key features of DI-JS is the ability to override bound values. Recall that there are two kinds of bindings: global and local binding. There is a third type of binding called "run context" binding. A "run context" binding is a local binding who is an ancestor of a run context. For example:
DIJS ;
When DI-JS resolves a key, it looks in three different places, in this order:
- The local bindings visible to the provider.
- The run context binding.
- The global binding.
This means that, from a run context, you can only override global bindings. For example:
DIJS ; DIJS ;
Note that the value of 'a'
is different in run provider and in the provider of 'c'
.