我对类的属性使用 @bindable
装饰器没有问题。
例如
export class SomeClass {
@bindable public SomeProperty: Date = new Date();
}
但是当涉及到将它与具有 getter/setter 实现的属性一起使用时,我感到很困惑。例如
export class SomeClass2 {
// Where should the @bindable go now?
private _someProperty: Date = new Date();
public get SomeProperty(): Date {
return this._someProperty;
}
public set SomeProperty(value: Date) {
// Do some manipulation / validation here
this._someProperty = value;
}
}
我确定我在这里遗漏了一些简单的东西......
最佳答案
Bindable 通过在您用于观察变化的属性上添加一个 getter 和一个 setter 来工作。建议您使用 ${propertyName}Changed(newValue, oldValue)
回调方法来完成您要执行的操作。这是一个 ES2016 示例:
View 模型
import {bindable} from 'aurelia-framework';
export class MyCustomElement {
@bindable name;
_name;
errorMessage = '';
nameChanged(newValue) {
if(newValue.length >= 5 ) {
this.errorMessage = 'Name is too long';
}
else {
this._name = newValue;
this.errorMessage = '';
}
}
}
查看
<template>
<p>Name is: ${_name}</p>
<p>Error is: ${errorMessage}</p>
</template>
请注意,由于 ES2016 没有私有(private)变量,我可以在我的 View 中使用私有(private)支持字段。我不确定您是否可以在 TypeScript 中执行此操作,但如果不能,请注意更改代码中 name
属性的值也会触发 nameChanged
回调触发。因此您需要检查 newValue
是否等于 this._name
并在这种情况下忽略它。
关于typescript - 如何在具有 getter 和 setter 的属性上使用 Aurelia 的可绑定(bind)装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36201809/