Giter Club home page Giter Club logo

di.js's Introduction

Angular - The modern web developer's platform

angular-logo
Angular is a development platform for building mobile and desktop web applications
using TypeScript/JavaScript and other languages.

angular.dev

Contributing Guidelines · Submit an Issue · Blog

CI status   Angular on npm   Discord conversation

InsightsSnapshot


Documentation

Get started with Angular, learn the fundamentals and explore advanced topics on our documentation website.

Advanced

Development Setup

Prerequisites

Setting Up a Project

Install the Angular CLI globally:

npm install -g @angular/cli

Create workspace:

ng new [PROJECT NAME]

Run the application:

cd [PROJECT NAME]
ng serve

Angular is cross-platform, fast, scalable, has incredible tooling, and is loved by millions.

Quickstart

Get started in 5 minutes.

Ecosystem

angular ecosystem logos

Changelog

Learn about the latest improvements.

Upgrading

Check out our upgrade guide to find out the best way to upgrade your project.

Contributing

Contributing Guidelines

Read through our contributing guidelines to learn about our submission process, coding rules, and more.

Want to Help?

Want to report a bug, contribute some code, or improve the documentation? Excellent! Read up on our guidelines for contributing and then check out one of our issues labeled as help wanted or good first issue.

Code of Conduct

Help us keep Angular open and inclusive. Please read and follow our Code of Conduct.

Community

Join the conversation and help the community.

Love Angular badge

Love Angular? Give our repo a star ⭐ ⬆️.

di.js's People

Contributors

btford avatar buchanae avatar caitp avatar despairblue avatar dmtrs avatar iammerrick avatar joliss avatar kalisjoshua avatar mikemcelroy avatar pkozlowski-opensource avatar rgbboy avatar rodyhaddad avatar rwaldron avatar shaselton avatar vojtajina avatar vsavkin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

di.js's Issues

Build issue

Having trouble running tests. I think it's because the traceur runtime is overwriting the Map class provided by es6-shim, and es6-shim assumes the Map class (which it provides) has a .keys() method, which it doesn't. Adding a line to es6-shim lets the tests run, but I have no idea if it is the "right" thing to do. Have submitted a PR to es6-shim for this because it does look like an oversight on their part.
paulmillr/es6-shim#245

Using Injector for non-singleton classes

Hey Vojta, thanks for di.js!

I'm wondering if there's a good way to use the Injector to create non-singleton classes. For instance, say we have

var amdTranspiler = new ES6Transpiler({
  target: 'amd',
  loader: 'myloader.js',
  ...
});

var nodeTranspiler = new ES6Transpiler({ ... });

And we'd like for the ES6Transpiler to take some injections. It seems that injector.get(ES6Transpiler) is fundamentally the wrong way, since it's used for singletons.

We could just pass the injector as the first constructor argument,

var injector = new Injector([]);
var amdTranspiler = new ES6Transpiler(injector, { ... });

But it seems that this makes the implementation inside of ES6Transpiler rather ugly, since we don't get to use annotations, so we'd have to do injector.get(Foo) inside of the ES6Transpiler constructor.

I'm thinking we could add an injector.create method for this, which works like .get, but doesn't cache - but I haven't thought this through at all.

Do you have any thoughts on this? Are there existing patterns? Thanks :)

Examples Broken

Currently the examples are broken due to some 404s. It appears the build changed where some files are being placed. Also, some assumptions about requirejs node_module and traceur runtime file which are missing.

Error: Command failed: /bin/sh: 1: Google: not found after gulp serve

Hello

I receive error Error: Command failed: /bin/sh: 1: Google: not found after entering gulp serve in console. I'm not sure how imporant it is.

steps to reproduce the issue

$ git clone https://github.com/angular/di.js.git
$ cd di.js/
$ npm install
$ gulp build_examples
[19:37:31] Using gulpfile /.../di.js/gulpfile.js
[19:37:31] Starting 'build_examples'...
[19:37:31] Finished 'build_examples' after 7.44 ms
$ gulp serve
[19:37:39] Using gulpfile /.../di.js/gulpfile.js
[19:37:39] Starting 'serve'...
[19:37:39] Connect LiveReload on 35729 port
[19:37:39] Finished 'serve' after 8.72 ms
[19:37:39] Server started on 8000 port
[19:37:39] Error: Command failed: /bin/sh: 1: Google: not found

karma, karma-cli, gulp are installed

Node.js: How can I inject values or native node.js libraries?

Hi Vojta!

I am trying to use your DI in more real-life example code in node.js.

Maybe I just do not undestand it deep enough but what I struggle with is that I can't inject modules like fs or http (or just object literals like config etc.) into my module. Please see example:

// myclass.js
var di = require('di');
var fs = require("fs");

function MyClass (fileSystem) {
    this.fileSystem = fileSystem;
}


MyClass.prototype.doSomething = function () {

    //...

};


di.annotate(MyClass, new di.Inject(fs));

module.exports = MyClass;


// main.js
var di = require('di');
var MyClass = require('./myclass');


var injector = new di.Injector([]);

var mc = injector.get(MyClass); // No provider for [object Object]! (MyClass -> [object Object])
console.log(mc);

Maybe I just do not see it. Can you please provide some example?

Thank you,
Adam

Should a child injector inherit providers from its parent?

I have a system which creates child injectors which have a certain scope, SceneScope. RenderConfig is one class which has SceneScope.

In testing, I naturally wrote code to mock some config, RenderConfig, which has SceneScope, and provided MockRenderConfig to my root injector. This didn't work because the mock is provided to the root injector, but it's the child injector which creates the render config, due to scoping.

If I want to test this as is, I need to:
a) remove the scoping of RenderConfig. Maybe an option in this specific case, but probably not a robust solution.

b) write code which allows me more access to process of creating the child injectors, so I can modify the providers given to injector.createChild() from my test code. At a glance, this option feels messy.

It seems logical that a child injector would inherit its parent's providers. If so, my test should work as I originally wrote it, which would be a nice property.

Thanks.

feat: injectParent

For recursive data structure @InjectParent would allow to get hold of the parent instance in a nice way.

Cannot require di 1.9.0

di 1.9.0 fails with the following error message for me:

require('di')
Error: Cannot find module '../dist/cjs/src/annotations'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/ubuntu/src/broccoli/node_modules/di/node/index.js:12:19)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

Hm, by the way, could you perhaps re-publish the yanked 2.0.0-dev as 1.9.1? That way I can just update my package.json.

"karma start" and "gulp build" both broken on fresh clone

After git clone and npm install, tried running the project and immediately ran into errors:

$ karma start
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
ERROR [karma]: [Error: Unknown option: sourceMap]
Error: Unknown option: sourceMap
    at Error (<anonymous>)
...
$ gulp build
[16:00:45] Using gulpfile ~/WebstormProjects/di.js/gulpfile.js
[16:00:45] Starting 'build_source_cjs'...
[16:00:45] Finished 'build_source_cjs' after 7.79 ms
[16:00:45] Starting 'build_source_amd'...
[16:00:45] Finished 'build_source_amd' after 1.8 ms
[16:00:45] Starting 'build_dist'...
[16:00:45] Finished 'build_dist' after 6.34 μs
[16:00:45] Starting 'build_examples'...
[16:00:45] Finished 'build_examples' after 1.09 ms
[16:00:45] Starting 'build'...
[16:00:45] Finished 'build' after 8.37 μs

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: Unknown option: filename
    at Error (<anonymous>)

...

Publish to npm

CommonJS compiled version to make it available in Node.

injector.invoke

This apparently needs to be implemented. Do you have some ideas already for this, @vojtajina, or is this something we can hack on?

Injecting Generators is not working with latest update

@vojtajina the following code was working before. But it is not working after I updated to latest di.js code today. If API has been changed, please advice how I can fix this code.
I am also looking for better way to inject Diary's logger using di.js framework.
Thanks
Generators.js

import {Provide, ProvidePromise, TransientScope} from '../../../bower_components/angular-di/dist/amd/annotations';

// A generator for iterating over the keys in an object.
export function* keys(obj) {
    for (let key of Object.keys(obj)) {
        yield key;
    }
}

// A generator for iterating over the values in an object.
export function* values(obj) {
    for (let key of Object.keys(obj)) {
        yield obj[key];
    }
}

@TransientScope
@Provide('sumoKeyGen')
export function* keyGenerator() {
    for(var i=1; true; i++) {
        var reset = yield i;
        if(reset) { i = 0; }
    }
}

TodoItem.js

export default class TodoItem {
    constructor(text, done = false) {
        this.text = text;
        this.done = done;
    }

    toggle() {
        this.done = !this.done;
    }

    toString() {
        return this.text;
    }
}

TodoList.js

import Todo  from './TodoItem';
import {values, keys} from '../../common/utils/generators';
import {Inject} from '../../../bower_components/angular-di/dist/amd/annotations';
import {Diary} from '../../../bower_components/angular-diary/dist/amd/diary';

export default class TodoList {
    @Inject('sumoKeyGen')
    constructor(sumoKeyGen) {
        this.logger = Diary.logger('TodoList');
        this.keyGen = sumoKeyGen;
        // If Angular ng-repeat supported Maps, this could be a Map with integer keys.
        this.todos = {}; //new Map();
        this.length = 0; //map.size
    }

    add(text, done = false) {
        let todo = new Todo(text, done);
        let key = this.keyGen.next().value;
        this.todos[key] = todo;
        this.length++;
    }

    getTodo(key) {
        return this.todos[key];
    }

    remove(key) {
        delete this.todos[key];
        this.length--;
    }

    completed() {
        return this.todos.values().filter(todo => {
            return todo.done === true;
        });
    }

    remaining() {
        return this.todos.values().without(...this.completed());
    }

    clearAll() {
        for (let todo of keys(this.todos)) {
            this.remove(todo);
        }
        this.logger.info(`Reseting keyGen : ${this.keyGen.next(true).value}`);
    }

}

TodoController.js

import {Injector} from '../../../bower_components/angular-di/dist/amd/injector';
import TodoList from '../models/TodoList';

module generatorModule from '../../common/utils/generators';

export default class TodoController {

    constructor($scope, growl) {
        let injector = new Injector([generatorModule]);
        var todoList = injector.get(TodoList);
        todoList.add('learn AngularJS', true);
        todoList.add('build an AngularJS app');
        $scope.todos = todoList;
        $scope.newTodo = '';

        $scope.addTodo = () => {
            $scope.todos.add($scope.newTodo, false);
            growl.addInfoMessage(`${$scope.newTodo} ... added`, {ttl: 3000});
            $scope.newTodo = '';// clears input
        };

        $scope.removeTodo = (key) => {
            let anItem = $scope.todos.getTodo(key);
            growl.addWarnMessage(`${anItem.text} ... removed`, {ttl: 3000});
            $scope.todos.remove(key);
        };

        $scope.clearAll = () => {
            $scope.todos.clearAll();
            growl.addErrorMessage('All Clear', {ttl: 3000});
        };

        $scope.completed = () => {
            return $scope.todos.completed();
        };

        $scope.remaining = () => {
            return $scope.todos.remaining();
        };
    }

}

Docs for lazy injection

I have seen this mentioned sparingly in issues, but I can't get my head around how it should be used or what it does. It would be good to see some docs on this!

Node.js example: example/node/main.js broken

Hey,

Whenever I try to run the sample project or use [email protected] in my own project I get the following error.

module.js:340
    throw err;
          ^
Error: Cannot find module '../dist/cjs/index'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/seglo/source/foo/node_modules/di/node/index.js:12:18)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

Can not run di.js as instruction

I followed README.md but still can not run di.js as instruction.

When I run karma start, I got:

...
ERROR [preprocessor.traceur]: /Volumes/iMac/workspace/github/di.js/example/coffee/coffee_maker.js:6:1: Unexpected token @
ERROR [preprocessor.traceur]: /Volumes/iMac/workspace/github/di.js/example/coffee/coffee_maker.js:6:2: Semi-colon expected
ERROR [preprocessor.traceur]: /Volumes/iMac/workspace/github/di.js/example/coffee/electric_heater.js:5:1: Unexpected token @
ERROR [preprocessor.traceur]: /Volumes/iMac/workspace/github/di.js/example/coffee/electric_heater.js:5:2: Semi-colon expected
ERROR [preprocessor.traceur]: /Volumes/iMac/workspace/github/di.js/example/coffee/mock_heater.js:5:1: Unexpected token @
...
TEST RUN WAS CANCELLED because these files contain some errors:
    /Volumes/iMac/workspace/github/di.js/example/coffee/coffee_maker.js
    /Volumes/iMac/workspace/github/di.js/example/coffee/electric_heater.js
    /Volumes/iMac/workspace/github/di.js/example/coffee/mock_heater.js
    /Volumes/iMac/workspace/github/di.js/example/coffee/pump.js
    /Volumes/iMac/workspace/github/di.js/example/testing/mocks.js
    /Volumes/iMac/workspace/github/di.js/test/annotations.spec.js
    /Volumes/iMac/workspace/github/di.js/test/async.spec.js
    /Volumes/iMac/workspace/github/di.js/test/fixtures/house.js
    /Volumes/iMac/workspace/github/di.js/test/fixtures/shiny_house.js
    /Volumes/iMac/workspace/github/di.js/test/injector.spec.js

When I run gulp build, I got:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error in plugin 'gulp-traceur'

coffee_maker.js:6:1: Unexpected token @
coffee_maker.js:6:2: Semi-colon expected
    at Transform._transform (/Volumes/iMac/workspace/github/di.js/node_modules/gulp-traceur/index.js:44:23)
    at Transform._read (/Volumes/iMac/workspace/github/di.js/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at Transform._write (/Volumes/iMac/workspace/github/di.js/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/Volumes/iMac/workspace/github/di.js/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:238:10)
    at writeOrBuffer (/Volumes/iMac/workspace/github/di.js/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:228:5)
    at Transform.Writable.write (/Volumes/iMac/workspace/github/di.js/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:195:11)
    at write (/Volumes/iMac/workspace/github/di.js/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:605:24)
    at flow (/Volumes/iMac/workspace/github/di.js/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:614:7)
    at Transform.pipeOnReadable (/Volumes/iMac/workspace/github/di.js/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:646:5)
    at Transform.EventEmitter.emit (events.js:92:17)

Please help me out. What do I need to do in order to run it?
I lead AngularJS project in my company. It's interesting to take a look at new di.js framework too.

Thanks in advance!

Node module fails to browserify.

The node version of di.js fails to browserify because of the call require(require('traceur').RUNTIME_PATH);

Essentially browserify does not work with dynamic requires.

Changing this to require('traceur/bin/traceur-runtime') would fix this.

I understand that this then becomes more unstable if traceur decides to change where they keep this file. I did ask the traceur team if they would split out traceur runtime into its own package but they would prefer to keep traceur runtime in a specific location of their package here: google/traceur-compiler#828.

I have a pull request ready to be sent if you are OK with this change.

Can I use it with Angular 1.3.0?

I posted this on Stackoverflow and got a couple of likes but no answers, so I thought I would ask it here:

The new dependency injection that Volta spoke about at ng-conf and is contained here: https://github.com/angular/di.js is just what I am looking for for my AngularJS 1.3.0 project.

The problem is, it is not clear to me whether or not I can use it. There doesn't seem to be an example of using it for AngularJS v1 in the github project examples.

I came across an example using it in a Backbone project: http://teropa.info/blog/2014/03/18/using-angular-2-0-dependency-injection-in-a-backbone-app.html and I found an example of using ES6 in an AngularJS v1 project: https://github.com/mvolkmann/todo-es6/, but I can't find an example using the new DI in an Angular v1 project.

I'm confused. Any pointers?

Thanks for any help :)

How do I inject a class rather than an instance of a class?

This is a simplified version of what I am trying to do:

export class Factory {

  @Inject(MyClass)
  constructor (MyClass) {
    this.MyClass = MyClass;
  }

  create () {
    return new this.MyClass();
  }

}

export class MyClass {
  ...
}

Is there a way to get DI to pass a class rather than an instance of a class?

Feature: Inject class without intantiating

I'd like to be able to inject a un-instantiated class, so I can more easily mock classes for tests. Right now, here's what I'd have to do

function GetPromise () {
  return Promise;
}
@Inject(GetPromise)
class Deferred {
  constructor(Promise) {
    this.promise = new Promise();
  }
}

Modules should isolate configs

Hi di.js folks,

I recently opened an issue on the core Angular project asking for a way to isolate service/provider configuration per-module. It was closed as infeasible for v1.x, but @caitp suggested I open an issue here to put it on the radar for v2.

Original issue is here: angular/angular.js#8404

Thanks!

Ability to inject deps as an object?

Is this a good idea to create some annotation for class, so that injector would inject deps not as simple arguments, but as an object, i.e.:

@Inject(A, B)
class MyClass {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
}

instead do

@Inject({a: A, b: B})
class MyClass {
  constructor({a, b}) {
    this.a = a;
    this.b = b;
  }
}

or something like that?

bug(providers): methodless class instantiation broken in IE

This is an IE-only bug.

If you have a class, which has a constructor, but nothing on the prototype, then the FactoryProvider will be used instead of the ClassProvider. This causes this to be undefined in the constructor of the class during instantiation, which usually results in exceptions.

The name property of function is non-standard and not implemented in any version of IE up to now (11). However, you can polyfill name. See this stack overflow discussion for a simple implementation which appears to fix these issues, at least in my tests: http://stackoverflow.com/questions/6903762/function-name-not-supported-in-ie

Providing the polyfill inline here for convenience:

// Fix Function#name on browsers that do not support it (IE):
if (!(function f() {}).name) {
    Object.defineProperty(Function.prototype, 'name', {
        get: function() {
            var name = this.toString().match(/^\s*function\s*(\S*)\s*\(/)[1];
            // For better performance only parse once, and then cache the
            // result through a new accessor for repeated access.
            Object.defineProperty(this, 'name', { value: name });
            return name;
        }
    });
}

More node.js examples

Hi,

I'm new to angular/di and I'm trying to use this for in my server-side nodejs app. I would appreciate a couple more examples using this with nodejs manually without having to annotate everything. I have a large codebase already and changing everything would not work atm.

My DI is wrapped in a simple class context {get: function(name) {... }}. I have a need for some things to be resolved as a singleton, other things to be created as needed, and scopes - e.g. a global shared one and a request one, where I can dynamically add bindings.

ES6 Promises

I saw some new work related to promises and a question in the source regarding what library to use. The new ES6 Loader uses promises. I think it might be a good idea to use the same library/shim they do.

Tooling: linting

I decided against using the ES6++ syntax (@Inject annotations and type annotations) because of the poor linting support. For anyone who follows in my footsteps, here's the latest on the linter front at the time of writing: https://groups.google.com/d/msg/angular-dev/JdQHLzAA9xg/TcfpVCeEGGEJ

There is some discussion about ES6 support for ESLint here, although ES6++ has not been discussed: eslint/eslint#1291

There is an issue against JSHint specifically for ES6++ support: jshint/jshint#1789

I think a note about linter support belongs as a FAQ in the docs: "Should I use the ES6++ syntax in production?". The answer is probably no because you'll most likely lose the ability to lint.

Services defined on parent injector depending upon services defined in child injector

I want to have a root injector, which contains a provider for a service, A but I want to have a child injector that provides anothe service, B, which A depends upon:

module moduleB {
  @Provide(B)
  export function getB() { ... }
}

module moduleA {
  import {B} from modulateB;
  @Provide(A)
  export function getA(@Inject(B) b) { ... }
}

var rootInjector = new Injector([moduleA]);
var childInjector = new Injector([moduleB], rootInjector);

This doesn't work because you try the following:

childInjector.get(A);

The childInjector doesn't contain the A service so falls back to the rootInjector, which does. But then the params for A include B, an object that is only defined in the childInjector. Look up of the B object is only done on the rootInjector and so fails.

Now maybe this is the correct semantic, but it would prevent things like child injectors from overriding the services in a parent injector. I would imagine that a better algorithm would be to pass along the "youngest" (e.g. the child) injector along when looking up objects in a parent injector so that you can then "start again" at this youngest injector when looking up param dependencies of objects found in the parent injector.

how to compile into separate output files while using traceur with AMD option?

I am trying to compile your di files using grunt-traceur (not gulp-traceur) in my project.
all the options I tried with traceur is generating single output file instead of generating separate files. I would like to generate one output file for each input file , the same way as your gulp build process is doing.
I tried even your version of traceur-compiler without luck.
e.g., this command is generating single out/scripts/di/injector.js file with all imported modules.

/Developer/Applications/traceur-compiler-vojtajina/traceur --experimental --sourcemap --modules=amd --out out/scripts/di/injector.js app/scripts/di/injector.js

Please advice what the trick I have to do to get multiple output files.

Does a class need to have other member functions defined to be injected?

Following is a portion of a test. Here FuelDiesel is being injected into the instance of a Car class. However, if the start() method inside FuelDiesel is commented out (i.e. if the FuelDiesel class contains no other methods but the constructor()) then it fails the test saying:
TypeError: Cannot set property 'name' of undefined

    describe('a test', function(){
        class FuelDiesel {
            constructor(){
                this.name = 'Diesel';
            }
            //start(){}
        };
        @Inject(FuelDiesel)
        class Car{
            constructor(fuel){
                console.log(fuel);
                this.fuelType = fuel;   
            }
            start(){}
            getType(){ return 'Car';}
            getFuelType(){ return this.fuelType;}
        }
        var i = new Injector([]);
        var car = i.get(Car);
        it('should work', function(){
            expect(car.getType()).toBe('Car');
        });
    });

isClass and minification

I've been playing around with this and I believe I found a problem with the way it determines if it's a class when minified.

So this will use ClassProvider because the class name starts with uppercase:

class Person {
// code...
} 

when minified it will turn it into something along the lines of:

class r {
// code...
}

That will obviously throw errors because it will incorrectly use the FactoryProvider instead

The only way I've managed to make it work has been to write:

var Person = class {
// code...
}

This will obviously not have anything in the name property so it will work because it will not go into the if (clsOrFunction.name) block in the isClass function and check the prototype instead of the name.

I've been trying to think what else could work for determining if it's a class or not, but this seems like a tricky issue...

How can I instantiate a class with injected arguments and custom arguments?

export class MyClass {

  @Inject(Service)
  constructor (service, customArgument) {
    this.service = service;
  }

  ...

}

My application has many instances of MyClass each instantiated with different customArgumnent. Is there a way to get DI to provide the injected arguments? I was thinking something similar to how in angular you can provide locals to the $injector.instantiate(expression, locals):

injector.instantiate(MyClass, { customArgument: 'customArgument' });

Step back with import?

Hi Vojta!

I watched your presentation from ng-conf and I understand the motivations for the new DI module.
Still, I could not resist to write this (Sorry if this is not the right place).

Let me use your CoffeeMachine example a bit. Let's imagine I have several, let's say 10 parts from which the CoffeeMachine is build, all of them using Electricity dependency.

Let's just say that this is provided by the "PowerLineElectricity" implementation. All fine so far.

I understand that I can replace the implementation by mock by providing the mock to the injector. Still OK.

But what if I need to change the PowerLineElectricity implementation with the SolarElectricity implementation for 4 out of the 10 parts. If I got it right, I have to go to the 4 files and change the import there... With four files it is manageable, but how about 23 out of 50?

In our current project (node.js based, I admit), we are heavily using your previous version of DI framework. On top of it, we use a module which builds the dependency configuration for the injector out of the config file where we define all the dependencies. So, if I need to change 4 dependencies, I need to go to one file (knowing exactly which one) and change it for 4 items there.
I admit this is "string" based so minification unfriendly but maybe there is a better way than the one we are using one which would work with minification as well.

I was wondering whether there is any possibility to have something like that off the shelf with the new DI :-) Or, what disadvantages there might be with our approach?

If you wish, we can discuss it deeper in Czech as well, if you let me know how to contact you.

best

Michal

Pattern for decorating a provider?

class Service {}

@Provide(Service)
@Inject(Service)
function decorateService(service) {
  // decoration happens here
  // e.g. service.someFunc = function() { log('someFunc called'); };
  return service;
}

Currently this is a circular dependency error.

Is this something you think should be possible in di.js?

Route resolve syntax

I'm not sure if this is the appropriate venue for this question, but @btford explained that route resolvers would work differently under the new DI system. I was wondering if I could get some insight into what that should look like.

It can be as pseudo-code-y as you like, I'm just trying to get a sense for how the pieces should fit together.

Thanks!

@Providing a non-existent or arbitrary class name?

Can someone talk me through why, desired-behavior-wise, the MockHeater module needs to load the concrete Heater module in order to register itself? I feel like we should be able to create whatever module we want and say "This class is what I want the injector to respond with when it gets a request for X". Am I thinking about this poorly?

InjectLazy not exported in pre12

Hi,
I am using di pre12 and the InjectLazy annotation function is not exported.
I found this issue: #64. According to the resolution, it should be exported.

Is it a regression or an actual choice made to remove the InjectLazy annotation function?

Thank you,
JF

Dynamically initialise/inject

I’m trying to dynamically initialise/inject some modules. See my example below, with comments in the forEach.

Side note: I’m never sure when to use injector.get to initialise something vs. when to make something a dependency and let DI initialise it for me. Perhaps I’m misunderstanding DI.

// app.js

var endpointNames = [
    'user',
    'tweet'
];

var userService = {
    // Gets users
    get: function () {}
};

var tweetService = {
    // Gets tweets
    get: function () {}
};

var services = [userService, tweetService];

// Initialise the endpoints
endpointNames.forEach(function (endpointName) {
    // TODO: How do I ask for the endpoint I want to initialise? I could
    // probably do this with `injector.get`, but I feel like I want to inject it
    // to initialise it instead. If I rely on `injector.get` it means I have to
    // pass `injector` around in my application.
    // var Endpoint = require('./endpoints/' + endpointName);
    // var endpoint = injector.get(Endpoint);
    // endpoint(services);
});

// endpoints/user.js

exports = module.exports = UserEndpoint;

var di = require('di');
var Logger = require('../logger');

// Use DI to inject the logger
di.annotate(UserEndpoint, new di.Inject(Logger));
function UserEndpoint(logger) {
    // Manually inject the service
    return function (services) {

    };
}

// endpoints/tweet.js

// Use DI to inject the logger
exports = module.exports = TweetEndpoint;

var di = require('di');
var Logger = require('../logger');

// Use DI to inject the logger
di.annotate(TweetEndpoint, new di.Inject(Logger));
function TweetEndpoint(logger) {
    // Manually inject the service
    return function (services) {

    };
}

// logger.js
function Logger() {
    return {
        log: function () {}
    };
}

requesting a not yet cached instance from child injector stores the instance in the child injector and not in the root injector

As far as I understand, di works like this:

Requesting a not yet cached instance of a class on a child injector should create that instance on the root injector (unless specified otherwise when creating the child injector).
So the following test should pass, however, it fails:

     class SomeType {}
      iit('should work', ()=>{
        var injector = new Injector();
        var child = injector.createChild();
        var a = child.get(SomeType);
        var b = injector.get(SomeType);
        expect(a).toBe(b);
      });

Conflict when consumer is using Traceur runtime

I am unable to consume DI when I am running my app through Traceur’s runtime:

https://gist.github.com/OliverJAsh/fd5b5edb86d92a34d296

I get the following error:

/Users/Oliver/Development/di-test/node_modules/di/node_modules/traceur/bin/traceur-runtime.js:631
  var $__2 = $traceurRuntime.assertObject($traceurRuntime),
                             ^
TypeError: Object #<Object> has no method 'assertObject'
    at System.register.__moduleName (/Users/Oliver/Development/di-test/node_modules/di/node_modules/traceur/bin/traceur-runtime.js:631:30)
    at Object.<anonymous> (/Users/Oliver/Development/di-test/node_modules/di/node_modules/traceur/bin/traceur-runtime.js:776:3)
    at Module._compile (module.js:456:26)
    at Module._extensions..js (module.js:474:10)
    at Object.Module._extensions..js (/Users/Oliver/Development/di-test/node_modules/traceur/src/node/require.js:69:12)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/Users/Oliver/Development/di-test/node_modules/di/node/index.js:4:1)

Confused with examples

I'm a little confused about examples, I just wanted to try kitchekn-di and I cant find where is "source" (in EC6) and where is "compiled" (EC5) code. As I understand you have:
di.js / example / kitchen-di / index.html
which have reference to "compiled" directory and I don't understand which files I need to copy (for example) to my nginx to see that compiled version in current google chrome. Can you help me some how?

"Configuration" in di.js

Really just moving a question from angular/http here, https://github.com/angular/http/pull/26#issuecomment-46907522 --- I think we want to be able to have a configuration pass before the runtime of the application, as in angular 1.x, and my question is really just "how does that work?"

This has been talked about in design docs, but I haven't gotten the chance to do it yet in di.js, so I would like some pointers on the right approach to this.

(hint: I don't think requiring developers to create a parent injector with a bunch of values registered and injected into our service is really the right way to do it, that seems like a nightmare)

gulp build_examples - TypeError: Cannot read property 'arguments' of undefined

After cloning the repo, installing all dependencies with npm. Im still seeing this error "TypeError: Cannot read property 'arguments' of undefined" whenever I try to execute build_examples task. gulp build_dist works perfectly.

node v0.10.26
npm 1.4.4
osx

I deleted the local repo and tried again but Im still seeing the same error msg.

santiago :: Development/UnexpectedProfit/di.js ‹master*› » gulp build
[gulp] Using gulpfile /Users/sesteva/Development/UnexpectedProfit/di.js/gulpfile.js
[gulp] Starting 'build_source_cjs'...
[gulp] Finished 'build_source_cjs' after 5.03 ms
[gulp] Starting 'build_source_amd'...
[gulp] Finished 'build_source_amd' after 1.1 ms
[gulp] Starting 'build_dist'...
[gulp] Finished 'build_dist' after 7.1 μs
[gulp] Starting 'build_examples'...
[gulp] Finished 'build_examples' after 628 μs
[gulp] Starting 'build'...
[gulp] Finished 'build' after 5.4 μs

stream.js:94
      throw er; // Unhandled stream error in pipe.
            ^
TypeError: Cannot read property 'arguments' of undefined
    at TypeAssertionTransformer.transformBindingElementParameter_ (eval at <anonymous> (/Users/sesteva/Development/UnexpectedProfit/di.js/node_modules/pipe/node_modules/gulp-traceur/node_modules/traceur/src/node/traceur.js:24:17), <anonymous>:19188:25)
    at TypeAssertionTransformer.transformFormalParameter (eval at <anonymous> (/Users/sesteva/Development/UnexpectedProfit/di.js/node_modules/pipe/node_modules/gulp-traceur/node_modules/traceur/src/node/traceur.js:24:17), <anonymous>:19142:16)
    at FormalParameter.transform (eval at <anonymous> (/Users/sesteva/Development/UnexpectedProfit/di.js/node_modules/pipe/node_modules/gulp-traceur/node_modules/traceur/src/node/traceur.js:24:17), <anonymous>:3953:26)
    at TypeAssertionTransformer.transformAny (eval at <anonymous> (/Users/sesteva/Development/UnexpectedProfit/di.js/node_modules/pipe/node_modules/gulp-traceur/node_modules/traceur/src/node/traceur.js:24:17), <anonymous>:10093:27)
    at TypeAssertionTransformer.transformSetAccessor (eval at <anonymous> (/Users/sesteva/Development/UnexpectedProfit/di.js/node_modules/pipe/node_modules/gulp-traceur/node_modules/traceur/src/node/traceur.js:24:17), <anonymous>:10639:28)
    at Object.superCall (eval at <anonymous> (/Users/sesteva/Development/UnexpectedProfit/di.js/node_modules/pipe/node_modules/gulp-traceur/node_modules/traceur/src/node/traceur.js:24:17), <anonymous>:236:33)
    at TypeAssertionTransformer.transformSetAccessor (eval at <anonymous> (/Users/sesteva/Development/UnexpectedProfit/di.js/node_modules/pipe/node_modules/gulp-traceur/node_modules/traceur/src/node/traceur.js:24:17), <anonymous>:16148:30)
    at SetAccessor.transform (eval at <anonymous> (/Users/sesteva/Development/UnexpectedProfit/di.js/node_modules/pipe/node_modules/gulp-traceur/node_modules/traceur/src/node/traceur.js:24:17), <anonymous>:4553:26)
    at TypeAssertionTransformer.transformAny (eval at <anonymous> (/Users/sesteva/Development/UnexpectedProfit/di.js/node_modules/pipe/node_modules/gulp-traceur/node_modules/traceur/src/node/traceur.js:24:17), <anonymous>:10093:27)
    at TypeAssertionTransformer.transformList (eval at <anonymous> (/Users/sesteva/Development/UnexpectedProfit/di.js/node_modules/pipe/node_modules/gulp-traceur/node_modules/traceur/src/node/traceur.js:24:17), <anonymous>:10100:32)

Can use it in production

@vojtajina I see your comment that di.js will instead of node-di in #7 (comment) and npm's lastest version is 2.0.0-pre-2.

And write don't recommend using it in production in document how-can-i-use-it.md

My question is can I use it in production now or in the near future and when to release the stable 2.0.0 ver.

Cannot find module 'pipe/gulp'

 $ gulp build

module.js:340
    throw err;
          ^
Error: Cannot find module 'pipe/gulp'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (.../di.js/gulpfile.js:2:12)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

Error with gulp build

Hey,

I just cloned master and tried to run 'gulp build', which failed with the following output:

gulp build
[16:01:11] Using gulpfile ~/di.js/gulpfile.js
[16:01:11] Starting 'build_source_cjs'...
[16:01:11] Finished 'build_source_cjs' after 11 ms
[16:01:11] Starting 'build_source_amd'...
[16:01:11] Finished 'build_source_amd' after 2.28 ms
[16:01:11] Starting 'build_dist'...
[16:01:11] Finished 'build_dist' after 8.54 μs
[16:01:11] Starting 'build_examples'...
[16:01:11] Finished 'build_examples' after 1.21 ms
[16:01:11] Starting 'build'...
[16:01:11] Finished 'build' after 9.87 μs

events.js:72
throw er; // Unhandled 'error' event
^
Error in plugin 'gulp-traceur'

main.js:1:8: Semi-colon expected
main.js:1:21: Semi-colon expected
main.js:1:26: Semi-colon expected
at Transform._transform (/Users/cdion/di.js/node_modules/gulp-traceur/index.js:44:23)
at Transform._read (/Users/cdion/di.js/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:184:10)
at Transform._write (/Users/cdion/di.js/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:172:12)
at doWrite (/Users/cdion/di.js/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:238:10)
at writeOrBuffer (/Users/cdion/di.js/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:228:5)
at Transform.Writable.write (/Users/cdion/di.js/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:195:11)
at write (/Users/cdion/di.js/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:605:24)
at flow (/Users/cdion/di.js/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:614:7)
at Transform.pipeOnReadable (/Users/cdion/di.js/node_modules/gulp/node_modules/vinyl-fs/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:646:5)
at Transform.EventEmitter.emit (events.js:92:17)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.