【问题标题】:Aurelia observable with object property具有对象属性的 Aurelia 可观察
【发布时间】:2016-12-01 21:42:38
【问题描述】:

我正在尝试在 Aurelia 中的对象属性更改时进行监视。我以前没有使用过 observables,所以请帮助我。根据文档,这就是我认为可行的方法,但我怀疑这个点正在抛弃函数名称或可观察的。

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 的值时没有任何反应。

【问题讨论】:

    标签: aurelia observable


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!我希望避免这种情况,因为我没有包含很多属性以保持示例简单。我会观察接下来一两天是否有其他解决方案,如果没有,我会将您的解决方案标记为已接受的答案。感谢您抽出宝贵时间,法比奥!
    • 还有一个解决办法我会贴出来的
    • 查看更新后的答案!我看看有没有办法使用@observable
    • Fabio,我发现在我的 ev_date_startChanged(newValue, oldValue) 函数中,我无法访问我的视图模型或记录。如果我这样做 console.log(this.record.ev_date_end); 我会不确定。 this 对我不可用。你知道为什么吗?
    • 好吧,我发现如果我把.subscribe(this.ev_date_startChanged);改成.subscribe(() => this.ev_date_startChanged());就可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2017-09-07
    • 2012-12-12
    • 2021-03-30
    • 1970-01-01
    • 2016-12-28
    相关资源
    最近更新 更多