当 parent 与 Aurelia 中的组件类型相同时传递 parent

Passing the parent when parent is the same component type in Aurelia

编辑: 这个问题以前的标题是 "Getting parent via DI when parent is the same type in Aurelia" 但由于我的元素是如何嵌套的,所以只绑定 parent 更有意义添加到元素,因此已更改标题以反映这一点。

如果我有一个自定义元素,Thing,它有一个 child Thing(它有另一个 child Thing,等等),如何我可以在 class 相同时注入 parent 实例吗?

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

更复杂的是,根 Thing 元素将没有 parent,因此 DI 需要允许可选注入。

我不认为你的问题可以用 DI 来解决。 Thing 必须是 @transient 如果你想要它的多个实例。这意味着容器将不会保存对其创建的事物的引用。

这个问题看起来不正确或没有必要使用 DI。如果一个元素需要从其消费者接收一些特定输入数据,@bindable 将是我自然而然的第一个想法。那么在 Thing 中创建一个 @bindable parentThing 怎么样?

另一方面,如果您想要访问父绑定上下文,请考虑 bind() component life cycle

操作方法如下: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;
  }
}