UNPKG

2.24 kBPlain TextView Raw
1import {BoundViewFactory, ViewSlot, bindable, customAttribute, templateController} from 'aurelia-templating';
2import {inject} from 'aurelia-dependency-injection';
3import {IfCore} from './if-core';
4
5/**
6 * Binding to conditionally include or not include template logic depending on returned result
7 * - value should be Boolean or will be treated as such (truthy / falsey)
8 */
9@customAttribute('if')
10@templateController
11@inject(BoundViewFactory, ViewSlot)
12export class If extends IfCore {
13 @bindable({ primaryProperty: true }) condition: any;
14 @bindable swapOrder: 'before'|'with'|'after';
15 @bindable cache: boolean|string = true;
16
17 /**@internal*/
18 animating: any;
19 /**@internal*/
20 elseVm: any;
21
22 /**
23 * Binds the if to the binding context and override context
24 * @param bindingContext The binding context
25 * @param overrideContext An override context for binding.
26 */
27 bind(bindingContext, overrideContext) {
28 super.bind(bindingContext, overrideContext);
29 if (this.condition) {
30 this._show();
31 } else {
32 this._hide();
33 }
34 }
35
36 /**
37 * Invoked everytime value property changes.
38 * @param newValue The new value
39 */
40 conditionChanged(newValue) {
41 this._update(newValue);
42 }
43
44 /**
45 * @internal
46 */
47 _update(show) {
48 if (this.animating) {
49 return;
50 }
51
52 let promise;
53 if (this.elseVm) {
54 promise = show ? this._swap(this.elseVm, this) : this._swap(this, this.elseVm);
55 } else {
56 promise = show ? this._show() : this._hide();
57 }
58
59 if (promise) {
60 this.animating = true;
61 promise.then(() => {
62 this.animating = false;
63 if (this.condition !== this.showing) {
64 this._update(this.condition);
65 }
66 });
67 }
68 }
69
70 /**
71 * @internal
72 */
73 _swap(remove, add) {
74 switch (this.swapOrder) {
75 case 'before':
76 return Promise.resolve(add._show()).then(() => remove._hide());
77 case 'with':
78 return Promise.all([ remove._hide(), add._show() ]);
79 default: // "after", default and unknown values
80 let promise = remove._hide();
81 return promise ? promise.then(() => add._show()) : add._show();
82 }
83 }
84}