自定义元素内部的 Aurelia 自定义元素和共享变量

Aurelia Custom Elements Inside of Custom Elements & Sharing Variables

如何在自定义元素之间访问和共享变量?我有以下文件...

tip.html

<template>
    <div class="tip-container">
        <content select="tip-trigger"></content>
        <content select="tip-content"></content>
    </div>
</template>

tip.js

export class Tip {}

提示-trigger.html

<template>
    <span class="tip-trigger" click.trigger="showTip()">
        <content></content>
    </span>
</template>

提示-trigger.js

export class TipTrigger {
    showTip() {
        console.debug(this);
    }
}

提示-content.html

<template>
    <span class="tip">
        <content></content>
        <span class="tip__close  tip__close--default">×</span>
        <span class="tip__color"></span>
    </span>
</template>

提示-content.js

export class TipContent {}

在我的 Tip class 中,我想要一个变量名 visible。当 showTip 被触发时,visible 将被设置为 true,然后我将使用它在 tip-content.html 中添加一个 class。如何在这些自定义元素之间共享变量来执行此操作?

想法是创建一个元素来显示提示弹出窗口,其中任何类型的内容都可以作为触发器,并且在触发时可以显示任何类型的内容。基本示例:

<tip>
  <tip-trigger><button>?</button></tip-trigger>
  <tip-content><div>Here is some helpful info...</div></tip-content>
</tip>

Here 是您在 Plunker 中遇到的问题的解决方案。

请注意,tip-triggertip-content 元素只是模板的可替换部分。它们本身不需要成为组件(这让我在 "original" custom elements article 中很困惑)。

app.html:

<template>
  <require from="tip"></require>
  <tip>
      <tip-trigger><button>?</button></tip-trigger>
      <tip-content><div>Here is some helpful info...</div></tip-content>
  </tip>
</template>

tip.html:

<template>
    <div class="tip-container">
      <div>
         <div click.trigger="showContent()">
           <content select="tip-trigger"></content>
         </div>
      </div>
      <div show.bind="contentVisible">
        tip content:
        <content select="tip-content"></content>
      </div>
    </div> 
</template>

tip.js:

export class Tip {
  showContent(){
    this.contentVisible = !this.contentVisible;
  }
}

是否只需要将 Tip 转换为 service-like class 并导入?

export class Tip {
    constructor() {
        this.visible = false;
    }
    show() {
        this.visible = true;  // Or whatever to show the content
    }
    hide() {
        this.visible = false;
    }
}

然后:

import {inject} from 'aurelia-framework';  
import {Tip} from './tip';

@inject(Tip)
export class TipTrigger {
    constructor(tip) {
        this.tip = tip;
    }
    showTip() {
        this.tip.show();
        // Or I suppose you could access 'visible' directly
        // but I like the implementation details a method call offers.
    }
}

*免责声明:这是未经测试的。