2

所以我找到了如何使用下面显示的代码通过视图/视图槽动态构建和创建 Aurelia 自定义元素,但是,我不知道如何获取它的实例(我找到了一种方法,但它很难看)

这是我必须动态创建自定义元素的 util 服务

export class AureliaUtilService {
  constructor(
    private container: Container,
    private viewCompiler: ViewCompiler,
    private viewResources: ViewResources,
  ) { }

  createAureliaViewModelAddToSlot(templateUrl: string, bindableData: any, targetElement?: HTMLElement | Element, clearTargetContent = false): AureliaViewOutput | null {
    const viewFactory = this.viewCompiler.compile('<template><compose view-model.bind="template"></compose></template>', this.viewResources);

    if (targetElement) {
      if (clearTargetContent && targetElement.innerHTML) {
        targetElement.innerHTML = '';
      }

      // Creates a view
      const view = viewFactory.create(this.container);
      const bindings: any = { template: (templateUrl || ''), ...bindableData };

      view.bind(bindings, createOverrideContext(bindings));

      // Add the view to the slot
      const viewSlot = new ViewSlot(targetElement, true);
      if (viewSlot && viewSlot.add) {
        viewSlot.add(view);
      }
      return { view, viewSlot };
    }
    return null;
  }
}

然后我这样称呼它,我的自定义元素呈现在屏幕上,是的

const targetElm = document.querySelector('.container');
const templateUrl = PLATFORM.moduleName('custom-element');
const bindings = { collection: this.collection };
const dynamicElement = this.aureliaUtilService.createAureliaViewModelAddToSlot(templateUrl, bindings, targetElm, true);

但是现在我想要并且需要修改该自定义元素的一些属性,我怎样才能获得它的实例?通过在控制台中记录对象,我有点通过深入(真的很深)找到了实例,但它很难看,所以必须有更好的方法!?

这是我找到实例的深潜丑陋方式

// first I somehow need to wait the dynamically created Custom Element to fully rendered
// for that I found that I can wrap it in a setTimeout for a full lifecycle to pass
const instance = dynamicElement.view.children[0].children[0].container.viewModel;

// now I can change any of its properties
instance.selectedId = 123;

// I also need to watch for a property changes
// I found that I can do it this way
instance.selectedItemChanged = (item => console.log('item changed', item));

所以是的,它有效,但必须有更好的方法......对吗?

4

0 回答 0