Created
November 26, 2014 22:26
-
-
Save vojtajina/516199b89c7b38d71412 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Annotations can be put on: | |
// - functions / classes | |
// - function parameters | |
@Foo('bar') | |
function foo(@Baz() param1, @Baz() param2: Foo) {} | |
// GETS TRANSPILED INTO: | |
function foo() {} | |
// Using property getters, so that it works with circular references. | |
Object.defineProperty(foo, 'annotations', {get: function() { | |
return [new Foo('bar')]; | |
}}); | |
Object.defineProperty(foo, "parameters", {get: function() { | |
return [ | |
[new Baz], // annotations on param1 | |
[Foo, new Baz] // annotations on param2 | |
]; | |
}}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// An example of Dependency Injection using the annotations in runtime. | |
class Engine {} | |
class Car { | |
constructor(engine: Engine) {} | |
} | |
var injector = new Injector(); | |
var car = injector.get(Car); | |
// This is roughly what happens inside the `injector.get(Car)` call. | |
// - do I have an instance of Car (check a cache/map)? | |
// - if yes, return | |
// - if not, instantiate: | |
// - check Car.parameters annotations and instantiate the dependencies first: | |
// - var dep1 = injector.get(Car.parameters[0][0]); | |
// - return new Car(... already instantiated deps ...) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment