Aurelia可观察对象属性

时间:2016-11-30 17:22:39

标签: aurelia observable

我正试图在Aurelia中对象属性发生变化时设置监视。我之前没有使用过observable所以请帮助我。基于文档,这是我认为可行的,但我怀疑点是丢失函数名称或可观察的。

export class EventEdit {
  record = {
    ev_date_start,
    ev_date_end,
    ev_description
  };
  @observable record.ev_date_start;

  record.ev_date_startChanged(newValue, oldValue) {
    console.log("ev_date_start changed from " + oldValue + " to " + newValue);
  }
}

更改ev_date_start的值时没有任何反应。

1 个答案:

答案 0 :(得分:6)

当您需要复杂对象时,最好定义一个类。

import { observable } from 'aurelia-framework';

export class EventEdit {
  constructor() {
    this.model = new EventModel();

    setTimeout(() => {
      this.model.ev_date_start = "test";
    }, 2000);
  }
}

export class EventModel  {
    @observable ev_date_start;
    ev_date_end;
    ev_description;

    ev_date_startChanged(newValue, oldValue) {
      console.log("ev_date_start changed from " + oldValue + " to " + newValue);
    }
}

另一个解决方案是使用BindingEngine:

import {inject, BindingEngine} from 'aurelia-framework';

@inject(BindingEngine)
export class EventEdit {
  record = {
    ev_date_start,
    ev_date_end,
    ev_description
  };

  constructor(bindingEngine) {
    this.bindingEngine = bindingEngine;
  }

  attached() {
    this.subs = this.bindingEngine
       .propertyObserver(this.record, 'ev_date_start')
       .subscribe(this.ev_date_startChanged);
  }

  detached() {
    this.subs.dispose();
  }

  ev_date_startChanged(newValue, oldValue) {
    console.log("ev_date_start changed from " + oldValue + " to " + newValue);
  }
}
相关问题