typescript - 如何在具有 getter 和 setter 的属性上使用 Aurelia 的可绑定(bind)装饰器

标签 typescript aurelia

我对类的属性使用 @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/

相关文章:

javascript - 如果未在配置文件中设置实体目录,则 TypeORM 无法找到实体

javascript - 带有实例变量的引用给出错误

node.js - 尝试在 Typescript 中跨不同文件共享接口(interface)时出错

angular - 将按钮添加到谷歌地图 Angular2

aurelia - 将 humane.js 与 aurelia 结合使用

html - 将 HTML5 拖放与 Aurelia 结合使用

node.js - gulp-typescript 无法转译我的项目 ts 文件

aurelia - 如何提供一个 aurelia 库供基于 aurelia CLI 的应用程序使用

azure - 如何在 Azure Web Apps 上释放锁定的文件? (以前是 : jspm install issues)

aurelia - Aurelia中父子自定义元素的双向绑定(bind)