2016-04-23 24 views
3

編輯:此問題的標題是「當父母在Aurelia中是同一類型時通過DI獲得父母」,但由於我的元素嵌套,更有意義的是將父元素綁定到元素,所以標題已經改變以反映這一點。當父母在Aurelia中是相同的組件類型時,通過父母

如果我有一個自定義元素,Thing其中有一個孩子Thing(具有另一個孩子Thing,等等),我怎麼能注入父實例當類是一樣的嗎?

export class Thing { 
    static inject = [Thing]; // <-- no reference to Thing as we are inside the class 
    constructor(parentThing) { 
     this.parent = parentThing; 
    } 
} 

作爲進一步的複雜性,根Thing元件將具有沒有父,所以DI需要允許用於可選注射。

+0

能告訴我爲什麼你堅持使用DI這種情況? – qtuan

+0

我認爲使用DI是有道理的,因爲您通常可以通過DI注入父項。儘管如此,你的方法是一個更好的策略。 – mark

回答

1

此問題對於使用DI來說看起來不正確或不必要。如果某個元素需要從其客戶那裏接收一些特定的輸入數據,那麼@bindable將是我首先想到的。那麼如何在Thing中創建@bindable parentThing

另一方面,如果您想要訪問父綁定上下文,請考慮bind()component life cycle

2

我不認爲你的問題可以用DI解決。 Thing必須是@transient如果你想有它的幾個實例。這意味着容器不會持有它創建的東西的引用。

0

這裏是如何做到這一點:https://gist.run?id=b075366d29f2400d3cc931f6fc26db24

app.html

<template> 
    <require from="./thing"></require> 

    <thing name="A"> 
    <thing name="B"> 
     <thing name="C"> 
     <thing name="D"> 
     </thing> 
     </thing> 
    </thing> 
    </thing> 
</template> 

app.js

export class App { 
} 

可選,parent.js

import {resolver} from 'aurelia-dependency-injection'; 

@resolver() 
export class OptionalParent { 
    constructor(key) { 
    this.key = key; 
    } 

    get(container) { 
    if (container.parent && container.parent.hasResolver(this.key, false)) { 
     return container.parent.get(this.key) 
    } 
    return null; 
    } 

    static of(key) { 
    return new OptionalParent(key); 
    } 
} 

thing.html

<template> 
    <h3> 
    My Name is "${name}". 
    <span if.bind="parent">My parent's name is "${parent.name}".</span> 
    <span if.bind="!parent">I don't have a parent.</span> 
    </h3> 
    <content></content> 
</template> 

thing.js

import {bindable, inject} from 'aurelia-framework'; 
import {OptionalParent} from './optional-parent'; 

@inject(OptionalParent.of(Thing)) 
export class Thing { 
    @bindable name; 

    constructor(parent) { 
    this.parent = parent; 
    } 
} 
+0

不幸的是,在我的代碼中,'Thing'解決了在thing.js和OptionalParent的構造函數中未定義的類。這似乎與GistRun示例有所不同。 – mark

+0

我們需要查看您的代碼,以瞭解您的意思 –

+0

對不起,我很生氣,但它很簡單。類名Thing(在我的代碼OFC中是不同的)字面上解析爲'undefined'。我很懷疑我的巴別塔翻譯是怪人。 – mark