I am working on an existing SPA where we replace components with Aurelia components step by step. We use the enhance
API of the TemplatingEngine
. That
View
returned from the enhance()
method.The enhance()
method returns the enhanced View
object. It is a good practice to manage the teardown from the same location where you call enhance()
, as you may not be able to trust an element to remember to tear itself down. However, you can always register the View
instance with the enhance container to access it from within the custom element.
function proceed() {
let aurelia = window.DFAurelia;
let container = aurelia.container;
let engine = container.get(TemplatingEngine);
let view = engine.enhance({
container: container,
element: targetElement,
resources: aurelia.resources
});
container.registerInstance(View, view);
}
This will tell the DI container to respond to calls for View
with this View
.
import { inject, Aurelia, View } from 'aurelia-framework';
@inject(Aurelia, Element)
export class DFCustomElement {
// element is passed to the constructor
constructor(aurelia, element) {
this.container = aurelia.container;
this.element = element;
}
// but View is only available after attached
attached() {
this.view = this.container.get(View);
}
removeMyself() {
this.element.remove();
this.view.detached();
this.view.unbind();
}
}
created(view)
lifecycle methodA much better practice would be to use the created(view)
lifecycle method in your custom element.
import { inject } from 'aurelia-framework';
@inject(Element)
export class DFCustomElement {
constructor(element) {
this.element = element;
}
created(view) {
this.view = view;
}
removeMyself() {
this.element.remove();
this.view.detached();
this.view.unbind();
}
}
This is a much more straightforward, best practices way of having a custom element grab its own View
. However, when trying to write this answer for you, I tested nesting a custom element in a <compose>
element. The result was that the View
in my custom element was actually the View
for my <compose>
element, and removeMyself()
removed the <compose>
entirely.