首页 > 解决方案 > Aurelia:视图和视图模型的继承

问题描述

我正在构建一个 Aurelia 应用程序,它基本上允许用户为不同的资源显示不同的列表。这些列表共享一些功能,例如具有搜索和刷新功能的工具栏以及资源的分页列表。

我为单个资源创建了这个,一切都像一个魅力,但我现在需要为其他资源列表复制 TypeScript 代码和 HTML 的大部分。我决定采用不同的方法,使用一些命名的视图槽和一个抽象的视图模型创建一个自定义元素。这在第一次运行时有效,但在操作列表后它会立即停止更新插槽内容。

有没有办法实现我想要做的事情?

任何帮助,将不胜感激。

旁注:我尝试创建一个简单的 Gist 来演示该问题,但似乎我能找到的最新 CDN 版本还不支持视图槽(我无法让它工作)。:(

基本上我想做的是:

列表.html

<template>
    <div>list: ${counter}</div>
    <slot></slot>
    <button click.delegate="load()">Increase counter</button>
</template>

列表.ts

import { autoinject } from 'aurelia-dependency-injection';
import { customElement } from 'aurelia-templating';

@customElement('list')
@autoinject
export abstract class List {
    public abstract counter;
    public abstract load();
}

资源.html

<template>
    <require from="./list"></require>

    <list>
        <div>resource: ${counter}</div>
    </list>
</template>

资源.ts

import { autoinject } from 'aurelia-dependency-injection';
import { List } from './list';

@autoinject
export class App extends List {
    public counter = 0;

    constructor() {
        super();
    }

    public load() {
        this.counter++;
    }
}

这给出了以下输出:

list: 0
resource: 0
<button>Increase counter</button>

单击按钮后,它应该增加了列表和资源计数器,但它仍然显示资源的“ 0 ”。我的猜测是按钮正在调用抽象父类上的加载函数,该类没有实现,因此什么也不做。将按钮更改为子类会起作用,但并不能真正帮助我实现代码减少目标。如何继续使用实施者的(资源)绑定上下文?有办法吗?还是我完全偏离了轨道?

编辑
所以我找到了一种解决方法,但感觉不对。我更改了以下位List

@bindable({defaultBindingMode: bindingMode.twoWay}) public abstract counter:number;

然后在resourceHTML 中:

<list counter.bind="counter">
    <div>users: ${counter}</div>
</list>

这样,它会同步counter属性的绑定上下文。我希望有一种方法可以告诉 List 根本没有自己的绑定上下文,因为这在理论上可能会导致很多很多可绑定的。有谁知道我怎么能告诉List继承绑定上下文?

EDIT 2
为之前的 EDIT 找到了另一种解决方法,删除了可绑定行为并在组件中实现了bind回调。List这使我可以访问父绑定上下文作为第一个参数。我在List组件中本地保存,然后在counter属性更改时手动更新父绑定上下文。这仍然是一种解决方法,因为这会使List组件变得非常大,但让我不必担心资源中的绑定。现在List看起来像这样:

import { customElement } from 'aurelia-templating';
import { autoinject } from 'aurelia-dependency-injection';
import { observable } from 'aurelia-binding';

@customElement('list')
@autoinject
export abstract class List {
    private parentContext;
    @observable public abstract counter:number;

    bind(bindingContext) {
        this.parentContext = bindingContext;
    }

    counterChanged(newValue) {
        if (this.parentContext) this.parentContext.counter = newValue;
    }

    public abstract load();
}

我仍然对List完全删除组件的绑定上下文让它继承父绑定上下文的方法感兴趣。

注意这个GitHub 问题中提到的 instructions.inheritBindingContext就像一个one-time初始继承,因此在我的情况下没有用,但可能对其他人有用。

标签: typescriptaurelia

解决方案


看看这篇博 文 Aurelia Dynamic Compose 使用 compose 和 v-model 和 model,你可以在同一个列表中拥有不同的自定义元素


推荐阅读