[英]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 方法需要以下參數:
this
)訪問滿足我們要求的 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.