Aurelia Custom Attribute with setAttribute method()

萝らか妹 提交于 2019-12-02 02:03:24

You would have to manually trigger the Aurelia's enhance method for it to register the custom attributes or anything Aurelia related really. And you also have to pass in a ViewResources object containing the custom attribute.


Since this isn't as straight forward as you might think, I'll explain it a bit.

The enhance method requires the following parameters for this scenario:

  • Your HTML as plain text (string)
  • The binding context (in our scenario, it's just this)
  • A ViewResources object that has the required custom attribute

One way to get access to the ViewResources object that meets our requirements, is to require the custom attribute into your parent view and then use the parent view's ViewResources. To do that, require the view inside the parent view's HTML and then implement the created(owningView, thisView) callback in the controller. When it's fired, thisView will have a resources property, which is a ViewResources object that contains the require-d custom attribute.

Since I am HORRIBLE at explaining, please look into the example provided below.


Here is an example how to:

app.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);
  }
}

app.html

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

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

Gist.run:

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


Additional resources

Dwayne Charrington has written an excellent tutorial on this topic:

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

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