你如何使用ViewCompiler手动编译部分DOM? [英] How do you use ViewCompiler to manually compile part of the DOM?

查看:177
本文介绍了你如何使用ViewCompiler手动编译部分DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个简单的视图模型( widget.js ):

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";
    }
}

使用以下视图:( widget。 html ):

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

现在说我将这样的标记注入DOM:

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

我现在如何告诉Aurelia针对Widget的新实例编译这个新添加的DOM部分?我知道它涉及ViewCompiler,但需要一个例子来帮助我。我非常感谢任何帮助。谢谢!

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!

推荐答案

以下是一个例子: https://gist.run/?id=762c00133d5d5be624f9

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

它使用Aurelia的视图编译器进行编译html并创建一个视图实例,绑定到提供的视图模型。

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

用法:

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

这篇关于你如何使用ViewCompiler手动编译部分DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆