How do you use ViewCompiler to manually compile part of the DOM?

ぃ、小莉子 提交于 2019-12-30 07:24:29

问题


Say I have a simple view model (widget.js):

import {Behavior} from 'aurelia-framework';

export class Widget
{
    static metadata() { return Behavior.customElement('widget') }

    constructor()
    {
        this.title= "AwesomeWidget";
    }
}

With the following view: (widget.html):

<template>
    <div>${title}</div>
</template>

Now say I inject some markup like this into the DOM:

    var markup       = `<div><widget></widget></div>`;
    var $markup      = $(markup);
    var $placeholder = $("#placeholder");

    $placeholder.append($markup);

How can I now tell Aurelia to compile this newly added part of the DOM against a new instance of Widget? I know it involves ViewCompiler but need an example to help me along. I'd greatly appreciate any help. Thanks!


回答1:


A few months ago the TemplatingEngine class got a newly accessible enhance API method. This shortcuts the need to manually use the viewCompiler and compile method which was originally the only easy approach. This blog post details how you can use the enhance API to Aureliaify dynamically added HTML in your pages.

This has the added benefit of not needing to clean up the compiled HTML or detach anything either.




回答2:


Here's an example: https://gist.run/?id=762c00133d5d5be624f9

It uses Aurelia's view compiler to compile the html and create a view instance, bound to the supplied view-model.

view-factory.js

import {
  inject,
  ViewCompiler,
  ViewResources,
  Container,
  ViewSlot,
  createOverrideContext
} from 'aurelia-framework';

@inject(ViewCompiler, ViewResources)
export class ViewFactory {
  constructor(viewCompiler, resources, container) {
    this.viewCompiler = viewCompiler;
    this.resources = resources;
    this.container = container;
  }

  insert(containerElement, html, viewModel) {
    let viewFactory = this.viewCompiler.compile(html);
    let view = viewFactory.create(this.container);
    let anchorIsContainer = true;
    let viewSlot = new ViewSlot(containerElement, anchorIsContainer);
    viewSlot.add(view);
    view.bind(viewModel, createOverrideContext(viewModel));
    return () => {
      viewSlot.remove(view);
      view.unbind();
    };
  }
}

Usage:

let view = this.viewFactory.insert(containerElement, viewHtml, viewModel);


来源:https://stackoverflow.com/questions/29527389/how-do-you-use-viewcompiler-to-manually-compile-part-of-the-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!