typescript - 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;
然后在resource
HTML 中:
<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
初始继承,因此在我的情况下没有用,但可能对其他人有用。
解决方案
看看这篇博 文 Aurelia Dynamic Compose 使用 compose 和 v-model 和 model,你可以在同一个列表中拥有不同的自定义元素
推荐阅读
- laravel - Laravel 5.8 从两个不同的表中显示、更新、删除记录
- amazon-web-services - APIgateway + Lamba 测试有效,但部署的 API 导致 Lambda 超时
- c++ - 我怎样才能简化这个程序(字谜)?
- sql - 如何根据具有最大值的列过滤行?
- java - 嵌套的自动装配字段在 JUNIT 测试中保持为空
- javascript - 使用 Stripe V3 为卡创建条带令牌,但不使用前端的条带元素
- jquery - 传单:有时图层无法使鼠标事件起作用
- amazon-web-services - AWS EMR 使用 KMS 加密 S3 存储桶
- json - 使用 POST 请求将 WebApi 序列化为 Json
- deployment - 如何将 Tycho 构建的 p2 存储库部署到 Artifactory?