0.0.0 • Published 10 years ago

objar v0.0.0

Weekly downloads
1
License
MIT
Repository
github
Last release
10 years ago

objar Build status

Simple and fast dependency injection container

Installation

$ npm install objar --save
$ bower install objar --save

Usage

Defining and Resolving services

var objar = new Objar();

function Logger() {
    this.log = function (message) {
        console.log('Logged: ' + message);
    };
}

function ProductController(logger) {
    this.logger = logger;

    this.saveProduct = function () {
        this.logger.log('Saved the product!');
    };
}

// Defines the 'logger' service
objar.define('logger', function () {
   return new Logger();
});

// Defines the 'controller' service depending on the 'logger' service
objar.define('controller', function () {
    return new ProductController(this.resolve('logger'));
});

// Resolving the product controller service
var controller = objar.resolve('controller');

// => Logged: Saved the product!
controller.saveProduct();

The define() method accepts two parameters:

  • the service name
  • a function returning the service (it can be any value except undefined)

Inside the define() method you can reference objar with this to resolve services.

Services are created lazily when calling the resolve() method and it always returns the same instance (singleton)

Circular dependencies

When two services depend on each other (in)directly, an Error will be thrown showing the cycle path in order to help you to fix it.

// 'hello' depends on 'world'
objar.define('hello', function () {
    return 'hello' + this.resolve('world');
});

// 'world' depends on 'hello'
objar.define('world', function () {
    return 'world' + this.resolve('hello');
});

// Error: Circular dependency detected: hello -> world -> hello
objar.resolve('hello');

Invoking functions

You can invoke annotated functions depending on services (AngularJS way).

objar.define('hello', function () {
    return 'hello';
});

objar.define('world', function () {
    return 'world';
});

// Invoke the function with the services injected:
// - w: will be the 'hello' service
// - h: will be the 'world' service
objar.invoke(['hello', 'world', function (h, w) {
    // => hello world
    console.log(h + ' ' + w);
}]);

License

MIT