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

后端 未结 2 1084
温柔的废话
温柔的废话 2021-01-07 03:35

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

import {Behavior} from \'aurelia-framework\';

export class Widget
{
    static metadata() { return Beha         


        
2条回答
  •  醉酒成梦
    2021-01-07 04:06

    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);
    

提交回复
热议问题