当父级是Aurelia中的相同组件类型时传递父级

时间:2016-04-23 16:36:31

标签: aurelia aurelia-di

编辑:这个问题曾经标题为“当父级在Aurelia中的类型相同时通过DI获取父级”,但由于我的元素是如何嵌套的,因此绑定父级更有意义对于元素,所以标题已被更改以反映这一点。

如果我有一个自定义元素,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需要允许可选注入。

3 个答案:

答案 0 :(得分:2)

我认为你的问题不能用DI来解决。如果您想拥有多个实例,Thing必须为@transient。这意味着容器不会保存对其创建的内容的引用。

答案 1 :(得分:1)

使用DI时,此问题看起来不正确或必要。如果一个元素需要从其消费者那里接收一些特定的输入数据,那么@bindable将是我自然的第一思考。那么如何在REGEXP_INSTR( ly, '[efg]{4,6}', REGEXP_INSTR( ly, '[ab2]{2,5}[efg]{4,6}' ) ) 中创建@bindable parentThing

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

答案 2 :(得分: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;
  }
}