Skip to content

mikefrey/tinydi

Repository files navigation

tinydi

Tiny Dependency Injection for the browser

Features

  • Very small. < 60 SLOC, < 1kb minified
  • Resolves via function arguments or dependency array
  • Resolves registered modules and variables on window
  • No external dependencies

Limitations

  • Does not support module loading
  • Does not support circular dependencies
  • Function arg resolution breaks with minification

Basic Usage

Register some modules with di.reg(...)

di.reg('multiply', function() {
  return function(a, b) {
    return a * b
  }
})

di.reg('square', function(multiply) {
  return function(a) {
    return multiply(a, a)
  }
})

Set one or more entry points into the application using di.run(...) and start the app with di.start().

di.run(function(square) {
  square(4)
})

// in your on DOM Ready...
di.start()

Installation

Download tinydi.min.js and add a reference to your project:

<script src="/path/to/js/libs/tinydi.min.js"></script>

Or use bower:

$ bower install tinydi

API

di.reg(name, fn)

Registers a module with the given name and function. Resolves dependencies using fn arguments list.

di.reg('Car', function(Engine, Wheels, Chassis) {
  function Car() {
    // ...
  }
  return Car
})

di.reg(name, array)

Registers a module with the given name and function. The last item in the array must be the module function. Resolves dependencies using the strings provided in the array.

di.reg('Car', ['Engine', 'Wheel', 'Chassis', function(Engine, Wheels, Chassis) {
  function Car() {
    // ...
  }
  return Car
}])

di.run(fn)

Registers a function to be run when di.start() is called. Functions are run in the order they are registered. Resolves dependencies using fn arguments list.

di.run(function(Car) {
  var car = new Car()
  car.drive()
})

di.run(array)

Registers a function to be run when di.start() is called. Functions are run in the order they are registered. The last item in the array must be the module function. Resolves dependencies using the strings provided in the array.

di.run(['Car', function(Car) {
  var car = new Car()
  car.drive()
}])

di.start()

Runs the modules registered with di.run(). Call this whenever you'd like your application to start, such as onDomReady.

// using jQuery
$(di.start)

About

Tiny Dependency Injection for the browser

Resources

License

Stars

Watchers

Forks

Packages

No packages published