这里是如何做到这一点: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;
}
}
能告诉我为什么你坚持使用DI这种情况? – qtuan
我认为使用DI是有道理的,因为您通常可以通过DI注入父项。尽管如此,你的方法是一个更好的策略。 – mark