【问题标题】:Can a template be used with custom attribute in Aurelia?模板可以与 Aurelia 中的自定义属性一起使用吗?
【发布时间】:2017-05-15 21:32:44
【问题描述】:

尝试 Aurelia 功能,我想创建一个简单的自定义属性,根据与属性关联的模板将内容注入到定义属性的元素中。到目前为止,我只是为自定义属性创建视图和视图模型,并用属性注释元素,我没有运气。一个渲染模板如何与自定义属性关联。任何链接或信息将不胜感激。

按照 Charleh 的链接,我尝试实现它,虽然视图呈现,但它不会绑定我的项目。这是代码,也许有人可以发现问题所在

ctest.ts

import { inject, dynamicOptions, Container, customAttribute, bindable} from "aurelia-framework";
import {ViewEngine} from 'aurelia-templating';

@dynamicOptions
@customAttribute("my-test")
@inject(Element, Container, ViewEngine)
export class MyTestCustomAttribute { // extends Paging {

    constructor(private element: any,
        private container: Container,
        private viewEngine: ViewEngine) {

        this.element = element;
    }

    @bindable items = new Array<number>();

    @bindable totalItems: any;

    attached() {

        for (let i = 0; i < this.totalItems; i++) {
            this.items.push(i);
        }

        this.viewEngine.loadViewFactory('components/ctest/ctest.html').then(factory => {
            const childContainer = this.container.createChild();
            const view = factory.create(childContainer);
            view.bind(this);
        });
    }

    propertyChanged(name, newValue, oldValue) {
        switch (name) {
            case 'totalItems':
                alert("totalItems changed");
                break;
            case 'items':
                alert("items changed");
                break;
            default:
                break;
        }
    }
}

ctest.html

<template>
    hello from my-test
    <ul>
        <li repeat.for="item of items">
            ${item}
        </li>
    </ul>
</template>

和用法

也试过了

<div my-test="totalItems.bind:5"></div>

无论如何,this.totalItems 始终是未定义的。

更新

按照约定绑定 pascal case 属性名称的正确语法是使用“-”,所以这是正确的

<div my-test="total-items:5"></div>

【问题讨论】:

  • 自定义属性需要手动操作 DOM,因为默认情况下它们不会挂钩到诱人的引擎,但您也可以这样做。最新的 Aurelia 周刊对此有一篇文章
  • jeremyg.net/entry/… 这是帖子
  • 您可以使用模板引擎渲染模板,然后将结果作为其附加到的元素的子元素插入到 DOM 中
  • @Charleh 感谢您的链接。关于您的最后一条评论,您是否有关于如何执行此操作的链接?来自 Angular 并尝试学习 Aurelia...
  • 可能你忘了加&lt;div my-test="total-items.bind:5"&gt;&lt;/div&gt;

标签: aurelia


【解决方案1】:

这就是我最终做的事情,到目前为止它似乎工作正常

public attached(): void {

    this.viewEngine.loadViewFactory('components/pagination/PaginationCustomAttribute.html').then(factory => {

        const childContainer = this.container.createChild();
        const view = factory.create(childContainer);

        view.bind(this);

        this.totalPages = this.calculateTotalPages();
        this.updatePage();

        const vs = new ViewSlot(this.element, true);
        vs.add(view);
    });
}

【讨论】:

    猜你喜欢
    • 2017-05-07
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    相关资源
    最近更新 更多