angular-cn/public/docs/js/latest/api/di/BindingBuilder-class.jade

185 lines
3.6 KiB
Plaintext

p.location-badge.
exported from <a href='../di'>angular2/di</a>
defined in <a href="https://github.com/angular/angular/tree/2.0.0-alpha.32/modules/angular2/src/di/binding.ts#L259-L372">angular2/src/di/binding.ts (line 259)</a>
:markdown
Helper class for the <a href='bind-function.html'><code>bind</code></a> function.
.l-main-section
h2 Members
.l-sub-section
h3 constructor
pre.prettyprint
code.
constructor(token: any)
:markdown
.l-sub-section
h3 token
:markdown
.l-sub-section
h3 toClass
pre.prettyprint
code.
toClass(type: Type)
:markdown
Binds an interface to an implementation / subclass.
Because `toAlias` and `toClass` are often confused, the example contains both use cases for
easy comparison.
```javascript
class Vehicle {}
class Car extends Vehicle {}
var injectorClass = Injector.resolveAndCreate([
Car,
bind(Vehicle).toClass(Car)
]);
var injectorAlias = Injector.resolveAndCreate([
Car,
bind(Vehicle).toAlias(Car)
]);
expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
```
.l-sub-section
h3 toValue
pre.prettyprint
code.
toValue(value: any)
:markdown
Binds a key to a value.
```javascript
var injector = Injector.resolveAndCreate([
bind(String).toValue('Hello')
]);
expect(injector.get(String)).toEqual('Hello');
```
.l-sub-section
h3 toAlias
pre.prettyprint
code.
toAlias(aliasToken: /*Type*/ any)
:markdown
Binds a key to the alias for an existing key.
An alias means that we will return the same instance as if the alias token was used. (This is
in contrast to `toClass` where a separate instance of `toClass` will be returned.)
Becuse `toAlias` and `toClass` are often confused, the example contains both use cases for easy
comparison.
```javascript
class Vehicle {}
class Car extends Vehicle {}
var injectorAlias = Injector.resolveAndCreate([
Car,
bind(Vehicle).toAlias(Car)
]);
var injectorClass = Injector.resolveAndCreate([
Car,
bind(Vehicle).toClass(Car)
]);
expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
```
.l-sub-section
h3 toFactory
pre.prettyprint
code.
toFactory(factoryFunction: Function, dependencies?: List&lt;any&gt;)
:markdown
Binds a key to a function which computes the value.
```javascript
var injector = Injector.resolveAndCreate([
bind(Number).toFactory(() => { return 1+2; }),
bind(String).toFactory((v) => { return "Value: " + v; }, [Number])
]);
expect(injector.get(Number)).toEqual(3);
expect(injector.get(String)).toEqual('Value: 3');
```