我没有问题使用@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;
}
}
我确定这里缺少一些简单的东西...
可绑定的工作原理是在用于观察更改的属性上添加一个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 = '';
}
}
}
看法
<template>
<p>Name is: ${_name}</p>
<p>Error is: ${errorMessage}</p>
</template>
请注意,由于ES2016没有私有变量,因此我可以在View中使用私有后备字段。我不确定是否可以在TypeScript中执行此操作,但是请注意,更改name
代码中属性的值也会触发nameChanged
回调触发。因此,在这种情况下,您需要检查是否newValue
等于this._name
并忽略它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句