如何在具有getter和setter

时间:2016-03-24 13:51:53

标签: typescript aurelia aurelia-binding

对于类的属性,使用@bindable装饰器没有问题。 E.g。

export class SomeClass {
    @bindable public SomeProperty: Date = new Date();
}

但是当我将它与具有getter / setter实现的属性一起使用时,我感到很难过。 E.g。

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;
    }
}

我确定我在这里错过了一些简单的事情......

1 个答案:

答案 0 :(得分:8)

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 = '';
    }
  }
}

查看

<template>
  <p>Name is: ${_name}</p>
  <p>Error is: ${errorMessage}</p>
</template>

请注意,由于ES2016没有私有变量,因此我可以在视图中使用私有支持字段。我不确定您是否可以在TypeScript中执行此操作,但如果您不能这样做,请注意更改代码中name属性的值也会触发nameChanged回击起火。因此,您需要检查newValue是否等于this._name并在这种情况下忽略它。