繁体   English   中英

带有 setAttribute 方法的 Aurelia 自定义属性()

[英]Aurelia Custom Attribute with setAttribute method()

当我在 javascript 中创建和附加元素并设置自定义属性时,Aurelia 似乎不知道(除非我做错了什么)。 例如,

const e = document.createElement('div');
e.setAttribute('custom-attr', 'some value');
body.appendChild(e);

有没有办法让 Aurelia 在附加时知道这个自定义属性?

一点背景:我正在创建一个应用程序,用户可以在其中选择他们的元素类型(例如输入、选择、复选框等)并拖动它(拖动是在自定义属性中完成的)。 我想过创建一个包装器<div custom-attr repeat.for="e of elements"></div>并以某种方式呈现元素数组,但这似乎效率低下,因为每次我推送一个新元素时,转发器都会遍历所有元素一个,我不想为可能创建的文本输入这样简单的东西创建一个包装器。

您必须手动触发 Aurelia 的enhance方法才能注册自定义属性或任何真正与 Aurelia 相关的内容。 并且您还必须传入包含自定义属性的 ViewResources 对象。


由于这并不像您想象的那么直接,我将解释一下。

对于这种情况,enhance 方法需要以下参数:

  • 您的 HTML 为纯文本(字符串)
  • 绑定上下文(在我们的场景中,就是this
  • 具有所需自定义属性的 ViewResources 对象

访问满足我们要求的 ViewResources 对象的一种方法是将自定义属性require到您的父视图中,然后使用父视图的ViewResources 为此, require父视图的 HTML 中的视图,然后在控制器中实现created(owningView, thisView)回调。 当它被触发时, thisView将有一个resources属性,它是一个包含require -d 自定义属性的 ViewResources 对象。

由于我无法解释,请查看下面提供的示例。


这是一个示例,如何:

应用程序.js

import { TemplatingEngine } from 'aurelia-framework';

export class App {
  static inject = [TemplatingEngine];

  message = 'Hello World!';

  constructor(templatingEngine, viewResources) {
    this._templatingEngine = templatingEngine;
  }

  created(owningView, thisView) {
    this._viewResources = thisView.resources;
  }

  bind() {
    this.createEnhanceAppend();
  }

  createEnhanceAppend() {
    const span = document.createElement('span');
    span.innerHTML = "<h5 example.bind=\"message\"></h5>";
    this._templatingEngine.enhance({ element: span, bindingContext: this, resources: this._viewResources });
    this.view.appendChild(span);
  }
}

应用程序.html

<template>
  <require from="./example-custom-attribute"></require>

  <div ref="view"></div>
</template>

要点运行:

https://gist.run/?id=7b80d2498ed17bcb88f17b17c6f73fb9


其他资源

Dwayne Charrington 写了一篇关于这个主题的优秀教程:

https://ilikekillnerds.com/2016/01/enhancing-at-will-using-aurelias-templating-engine-enhance-api/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM