javascript - 属性(property)观察员与自制设置员

标签 javascript typescript aurelia

在 aurelia View 模型中,我有一些属性需要在每次更改其他属性时更新。

据我所知,有两种不同的方法可以做到这一点。

方法1:propertyObserver

export class Foo {
    propX : number;
    bindingEngine : BindingEngine;

    bind() {
        this.bindingEngine.propertyObserver(this, 'propX')
            .subscribe((newV, oldV) => { this.updateOtherProperty() });
    }

    updateOtherProperty() {
        //...
    }
}

// usage
foo.propX = 5 // updateOtherProperty gets called

方法2:自制setter

export class Foo2 {
    propX : number;

    setPropX(value : number) {
        this.propX = value;
        this.updateOtherProperty();
    }

    updateOtherProperty() {
        //...
    }
}

// usage
foo.setPropX(5) // updateOtherProperty gets called

最好的方法是什么?为什么?

最佳答案

使用计算属性:

import { computedFrom } from 'aurelia-framework';

export class MyClass {

  @computedFrom('propX', 'propY') //update this property whenever propX or propY change
  get myComputedProp() {
    //do your magic here!
    return this.propX + this.propY;
  }

}

用法:

<div>${myComputedProp}</div>

更多信息请访问:http://aurelia.io/hub.html#/doc/article/aurelia/binding/latest/binding-computed-properties/1

关于javascript - 属性(property)观察员与自制设置员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44108766/

相关文章:

javascript - 错误 : Cannot invoke an expression whose type lacks a call signature

node.js - au run - 应用程序包中不包含 js 文件

javascript - 所有数组值都相同时的拼接问题

javascript - 如何对使用 "compose"构建的自定义元素进行单元测试?

javascript - aurelia 中的登录页面

javascript - 禁用 Csrf 进行 ajax 查询

javascript - 上下文中 jQuery.ajax() 中出现意外标识符

javascript - 将单选按钮数值打印到文本框

javascript:为什么要 "sign-prefix"一个变量?

regex - 使用正则表达式的 Angular 模式验证