UNPKG

1.56 kBPlain TextView Raw
1import { inject } from 'aurelia-dependency-injection';
2import { BoundViewFactory, customAttribute, templateController, ViewSlot } from 'aurelia-templating';
3import { IfCore } from './if-core';
4
5@customAttribute('else')
6@templateController
7@inject(BoundViewFactory, ViewSlot)
8export class Else extends IfCore {
9
10 /**
11 * @internal
12 */
13 ifVm: any;
14
15 constructor(viewFactory, viewSlot) {
16 super(viewFactory, viewSlot);
17 this._registerInIf();
18 }
19
20 bind(bindingContext, overrideContext) {
21 super.bind(bindingContext, overrideContext);
22 // Render on initial
23 if (this.ifVm.condition) {
24 this._hide();
25 } else {
26 this._show();
27 }
28 }
29
30 /**
31 * @internal
32 */
33 _registerInIf() {
34 // We support the pattern <div if.bind="x"></div><div else></div>.
35 // Obvisouly between the two, we must accepts text (spaces) and comments.
36 // The `if` node is expected to be a comment anchor, because of `@templateController`.
37 // To simplify the code we basically walk up to the first Aurelia predecessor,
38 // so having static tags in between (no binding) would work but is not intended to be supported.
39 let previous = (this.viewSlot as ViewSlot & { anchor: any}).anchor.previousSibling;
40 while (previous && !previous.au) {
41 previous = previous.previousSibling;
42 }
43 if (!previous || !previous.au.if) {
44 throw new Error("Can't find matching If for Else custom attribute.");
45 }
46 this.ifVm = previous.au.if.viewModel;
47 this.ifVm.elseVm = this;
48 }
49}