Skip to content

Instantly share code, notes, and snippets.

@groundwater
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save groundwater/5b3a90337d19f9bb7a0a to your computer and use it in GitHub Desktop.
Save groundwater/5b3a90337d19f9bb7a0a to your computer and use it in GitHub Desktop.
JavaScript Modules and Dependency Injection
import {Router} from './myRouter'
import {Component} from './myComponent' with {Router} // inject Router into imported module
const component = new Component()
component.doSomething()
import {Router} // injected by parent
export class Component {
constructor() {
this.router = new Router() // this is injected by the parent module
}
doSomething() {
this.router.doSomething()
}
}
// myComponent.js
module.exports = function(Router) {
function Component() {
this.router = new Router()
}
Component.prototype.doSomething = function(){
this.router.doSomething()
}
return {Component: Component}
}
// index.js
var Router = require('./myRouter').Router
var Component = require('./myComponent')(Router).Component // inject Router into imported module
const component = new Component()
component.doSomething()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment