needle-js

Angular.js style dependency injection using reflection.

npm install needle-js
1 downloads in the last week
4 downloads in the last month

Needle.js

 

Isolated concept of Angular's $injector using dependency injection and reflection for JavaScript constructors.

Needle is perfect for testing because dependencies aren't hard-coded. You can easily create mocks of your object's dependencies and pass them in on instantiation.

Flow

Needle.js Flow

  • Any constructor method on the class will be invoked, passing the args as individual args (not an array);
  • Any prototype property defined on the class will be instantiated and set to __proto__ to configure the prototype chain;

Usage

needle.registerInjector('decorator', Decorator);
var name = needle.invoke(NameService);
console.log(name.myMethod());

In addition to the needle.invoke way, if you invoke needle.applyPrototypes then you will have access to the invoke method on each one of your functions. Therefore the following would be possible:

needle.registerInjector('decorator', Decorator);
var name = NameService.invoke();
console.log(name.myMethod());

Steps

  • Create your object, specifying its dependencies:

    var Cats = function($dogs, $mice) { }
    
  • Create the two dependencies ($dogs and $mice -- the back-tick should be omitted when registering dependencies):

    needle.registerInjection('dogs', function() {});
    needle.registerInjection('mice', function() {});
    
  • Instantiate the Cats object:

    var cats = Cats.invoke();
    

    Voila! cats now has access to its dependencies -- $dogs and $mice!

Arguments

If the constructor method exists on your invoked constructor, then Needle will automatically invoke that method for you upon instantiation. Any arguments which you supply to the invoke method will also be served to your constructor method as individual arguments:

var NameService = function() {
    constructor: function(firstName, secondName, thirdName) { };
}
NameService.invoke('Bob', 'Jack', 'Alan');

Bundled Injectors

Needle.js also provides a handful of bundled injectors which you can use straight away without even registering them! Libraries/frameworks that we support must be included before the loading of Needle.

Name Injector Reference
jQuery $j
Underscore $u

Getting Started

To install Needle.js you need Grunt: npm install -g grunt. You'll also need npm.

Installing all of the Needle's dependencies is then quite simple: npm install.

Once you've installed the dependencies and Grunt you can:

  • Run all tests with grunt test;
  • Create a build with grunt;

Tests

All tests are written in Jasmine and can be run with grunt test.

npm loves you