Skip to content

Commit 8f77cef

Browse files
committed
feat(context): add support for context.add(binding)
1 parent 75eba76 commit 8f77cef

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

packages/context/src/context.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,25 +42,33 @@ export class Context {
4242
* Create a binding with the given key in the context. If a locked binding
4343
* already exists with the same key, an error will be thrown.
4444
*
45-
* @param key Binding key
45+
* @param keyOrBinding Binding key or a binding
4646
*/
4747
bind<ValueType = BoundValue>(
48-
key: BindingAddress<ValueType>,
48+
keyOrBinding: BindingAddress<ValueType> | Binding,
4949
): Binding<ValueType> {
50+
let key: string;
51+
let binding: Binding<ValueType>;
52+
if (keyOrBinding instanceof Binding) {
53+
key = keyOrBinding.key;
54+
binding = keyOrBinding;
55+
} else {
56+
key = keyOrBinding.toString();
57+
binding = new Binding<ValueType>(key);
58+
}
59+
5060
/* istanbul ignore if */
5161
if (debug.enabled) {
5262
debug('Adding binding: %s', key);
5363
}
54-
key = BindingKey.validate(key);
64+
5565
const keyExists = this.registry.has(key);
5666
if (keyExists) {
5767
const existingBinding = this.registry.get(key);
5868
const bindingIsLocked = existingBinding && existingBinding.isLocked;
5969
if (bindingIsLocked)
6070
throw new Error(`Cannot rebind key "${key}" to a locked binding`);
6171
}
62-
63-
const binding = new Binding<ValueType>(key);
6472
this.registry.set(key, binding);
6573
return binding;
6674
}

packages/context/test/unit/context.unit.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,13 @@ describe('Context', () => {
7171
expect(result).to.be.true();
7272
});
7373

74+
it('accepts a binding', () => {
75+
const binding = new Binding('foo').to('bar');
76+
expect(ctx.bind(binding)).to.be.exactly(binding);
77+
const result = ctx.contains('foo');
78+
expect(result).to.be.true();
79+
});
80+
7481
it('returns a binding', () => {
7582
const binding = ctx.bind('foo');
7683
expect(binding).to.be.instanceOf(Binding);

0 commit comments

Comments
 (0)