Module definitions are shared, on a per global scope basis; in other words,
the same module is defined only once per
window if running in a browser,
global if running under
Modules are defined by a
name, a list of dependencies, and a constructor
Constructors can return immediately (with a result), or can return a
Promise which will eventually resolve to the required instance.
Direct injection of a module is supported through the
which will return a
Promise to its return value:
Modules can also be directly required by the caller, and will be returned
wrapped into a
Multiple modules can also be requested simultaneously (both specifying module
names as arguments or an array of
Static vs. per-instance injection
In the examples above, a call to
new Esquire() will create a new injector
and with it, new modules instances are created. Each module instance is only
available to its injector, and never shared across.
On the other hand the global
esquire(...) method will allow to access a per
global scope shared injector.
esquire(...) with a callback function as its last parameter,
the method will behave like
inject(...), thus dependencies will be resolved
and passed to callback method, and its return value (if any) will be returned.
If no callback function was given, the
esquire(...) method will behave like
require(...) and simply return the required dependencies.
As module creation is asynchronous, it might be useful to specify a timeout when creation should fail.
By default the timeout is 2000 ms (2 sec), but a different timeout can be specified at construction time. The minimum timeout is 100 ms.
While optional, loading of external scripts is also supported, with the same
Promise mechanism (especially useful in browser environments).
Promises can be easily chained, constructs like the following can
be quite useful: