UNPKG

1.92 kBPlain TextView Raw
1import {inject} from 'aurelia-dependency-injection';
2import {BoundViewFactory, ViewSlot, customAttribute, templateController, ViewFactory} from 'aurelia-templating';
3import {createOverrideContext} from 'aurelia-binding';
4
5/**
6 * Creates a binding context for decandant elements to bind to.
7 */
8@customAttribute('with')
9@templateController
10@inject(BoundViewFactory, ViewSlot)
11export class With {
12
13 /**@internal*/
14 viewFactory: any;
15 /**@internal*/
16 viewSlot: any;
17 /**@internal*/
18 parentOverrideContext: any;
19 /**@internal*/
20 view: any;
21
22 value: any;
23
24 /**
25 * Creates an instance of With.
26 * @param viewFactory The factory generating the view.
27 * @param viewSlot The slot the view is injected in to.
28 */
29 constructor(viewFactory: ViewFactory, viewSlot: ViewSlot) {
30 this.viewFactory = viewFactory;
31 this.viewSlot = viewSlot;
32 this.parentOverrideContext = null;
33 this.view = null;
34 }
35
36 /**
37 * Binds the With with provided binding context and override context.
38 * @param bindingContext The binding context.
39 * @param overrideContext An override context for binding.
40 */
41 bind(bindingContext, overrideContext) {
42 this.parentOverrideContext = overrideContext;
43 this.valueChanged(this.value);
44 }
45
46 /**
47 * Invoked everytime the bound value changes.
48 * @param newValue The new value.
49 */
50 valueChanged(newValue) {
51 let overrideContext = createOverrideContext(newValue, this.parentOverrideContext);
52 let view = this.view;
53 if (!view) {
54 view = this.view = this.viewFactory.create();
55 view.bind(newValue, overrideContext);
56 this.viewSlot.add(view);
57 } else {
58 view.bind(newValue, overrideContext);
59 }
60 }
61
62 /**
63 * Unbinds With
64 */
65 unbind() {
66 let view = this.view;
67 this.parentOverrideContext = null;
68
69 if (view) {
70 view.unbind();
71 }
72 }
73}