needle-js

1.1.3 • Public • Published

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.new(NameService);
console.log(name.myMethod());

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

needle.registerInjector('decorator', Decorator);
var name = NameService.new();
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.new();

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 new method will also be served to your constructor method as individual arguments:

var NameService = function() {
    constructor: function(firstName, secondName, thirdName) { };
}
NameService.new('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.

Package Sidebar

Install

npm i needle-js

Weekly Downloads

2

Version

1.1.3

License

MIT

Last publish

Collaborators

  • wildhoney