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

Edit: This question was usually called “Getting a parent through DI when the parent is the same type in Aurelia”, but because my elements are nested, it makes sense to just bind the parent to the element, so the name has been changed to reflect this.

If I have a custom element, Thing , which has a child Thing (which has another child Thing , etc.), how can I insert a parent instance when the class is the same?

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

As an added complication, the Thing root element will not have a parent element, so the DI should include an additional injection.

+3
source share
3 answers

This issue does not appear to be correct or necessary for using DI. If an element needs to get some specific data from its consumer, then @bindable will be my natural first thinking. So, what about creating @bindable parentThing in Thing ?

Otherwise, if you want to access the context of the parent binding, consider bind() the component life cycle .

+1
source

I do not think your problem can be solved with DI. Thing must be @transient if you want to have multiple instances. This means that the container will not refer to what it creates.

+2
source

Here's how to do it: 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 { } 

optional-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 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
source

Source: https://habr.com/ru/post/1013627/


All Articles