2016-01-12 193 views
5

如何訪問自定義元素之間的共享變量&?我有以下的文件...自定義元素和共享變量中的Aurelia自定義元素

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類,我想有一個變量名visible。當showTip被觸發時,visible將被設置爲true,然後我將用它在tip-content.html中添加一個類。我如何分享這些自定義元素之間的變量來做到這一點?

這個想法是創建一個元素來顯示提示彈出窗口,其中任何類型的內容都可以作爲觸發器,並且觸發時可以顯示任何類型的內容。基本示例:

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

回答

1

你只需要打開Tip到服務類類並導入它?

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. 
    } 
} 

*免責聲明:這是未經測試。

+0

這是缺少的一塊。謝謝! – Dustin

+1

@David M. Brown我認爲如果你在視圖中添加2個提示是不行的,因爲注入應該創建單例(除非你在提示中使用'transient'裝飾器)。但事實是[它](http://plnkr.co/edit/5nwPD8rkRm2jWTBtw874?p=preview)。如果您使用不同的類來控制提示視圖[它確實表現爲單身人士](http://plnkr.co/edit/aA2YscqOaPkV5NUCiYe0?p=preview)。好奇... – DaniCE

+0

我也有同樣的擔憂。我仍然非常瞭解Aurelia和相關的東西是如何工作的。 – devguydavid

2

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; 
    } 
} 
+0

這簡單得多。謝謝! – Dustin

+1

假設我想給''或''添加屬性。那可能嗎?如果是這樣,我將如何訪問它們?這是你需要讓它們自己成爲組件的地方嗎?如果是這樣,那會把我帶回到我如何訪問組件間變量的原始問題。 – Dustin

+0

是的,在這種情況下,您需要'tip-trigger'和'tip-content'作爲組件。查看關於@David M. Brown的評論關於組件之間通信的回答。 – DaniCE

相關問題