How to tear down an enhanced fragment

前端 未结 1 410
遇见更好的自我
遇见更好的自我 2021-02-11 08:57

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

1条回答
  •  借酒劲吻你
    2021-02-11 09:47

    Use the 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();
      }
    }
    

    Using the created(view) lifecycle method

    A 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 element. The result was that the View in my custom element was actually the View for my element, and removeMyself() removed the entirely.

    0 讨论(0)
提交回复
热议问题