Jaa*_*ans 4 typescript aurelia aurelia-binding
我对使用@bindable类的属性的装饰器没有问题.例如
export class SomeClass {
@bindable public SomeProperty: Date = new Date();
}
Run Code Online (Sandbox Code Playgroud)
但是当我将它与具有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;
}
}
Run Code Online (Sandbox Code Playgroud)
我确定我在这里错过了一些简单的东西......
Bindable的工作原理是在您的属性上添加一个用于观察更改的getter和setter.建议您使用${propertyName}Changed(newValue, oldValue)回调方法来完成您尝试执行的操作.这是一个ES2016示例:
视图模型
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 = '';
}
}
}
Run Code Online (Sandbox Code Playgroud)
视图
<template>
<p>Name is: ${_name}</p>
<p>Error is: ${errorMessage}</p>
</template>
Run Code Online (Sandbox Code Playgroud)
请注意,由于ES2016没有私有变量,我可以在视图中使用私有支持字段.我不确定你是否可以在TypeScript中执行此操作,但如果不能,请注意name在代码中更改属性的值也会触发nameChanged要触发的回调.所以你需要检查是否newValue等于this._name并在这种情况下忽略它.
| 归档时间: |
|
| 查看次数: |
2379 次 |
| 最近记录: |