Incredibly simple, Dependency Injection for isomorphic Javascript applications.
The Problem
When using libraries such as React, React Router, & RefluxJS, you'll find that singletons don't work well on the server-side for Actions, Routes, Stores, & Views, as they share state between all requests.
On the client-side, each user's browser serves as a container to scope functions. Similarly, Diez introduces a container for each request on the server.
The Solution
Luckily, all it takes is to turn your singletons into factories by wrapping
them with function(...) { return ...; }
& registering them via diez.register
.
Diez will retrieve them while isolating instances to a single container-per-request.
Demo
Getting Started
Suppose you're rendering your React view on the server with React Router,
but rely on request
-specific data, such as the user's ip
, for some reason.
Step 0 - Install Diez
$ npm install --save diez
Step 1 - Create a container per request
In your application middleware:
// server.jsapp;
Now, every call to req.container.get('request')
returns req
.
React components with dependencies
Step 2 - InjectBefore, your view is a singleton:
// MyView.jsvar MyView = React; moduleexports = MyView;
After, your view is a factory with dependencies defined:
// MyView.jsvar diez = ; // Convert singleton to factoryvar { return React;}; // Register component with dependenciesdiez; moduleexports = MyView;
Step 3 - Retrieve injected components
app;
That's it!
License
The MIT License (MIT)
Copyright (c) 2015 Eric Clemmons
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.