繁体   English   中英

Aurelia bindingEngine.propertyObserver-检测由于对象更改而导致属性更改的时间

[英]Aurelia bindingEngine.propertyObserver - Detect when property changes due to object change

我们正在使用类似的代码来检测对特定对象属性的更改。

import {BindingEngine} from 'aurelia-framework';

class MyViewModel {
    static inject = [BindingEngine];

    constructor(bindingEngine) {
        this.bindingEngine = bindingEngine;
        this.myObject = {observeMe : 'Test' + new Date()};
    }

    attached() {
        this.subscription = this.bindingEngine
            .propertyObserver(this.myObject, 'observeMe')
            .subscribe((newValue, oldValue) => { 
                this.objectValueChanged(newValue, oldValue) 
            });

        setInterval(() => {
            this.myObject.observeMe = 'Test' + new Date();
        }, 2000);
    }

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

    objectValueChanged(newValue, oldValue) {
        console.log(`observeMe value changed from: ${oldValue} to:${newValue}`);
    }
}

https://discourse.aurelia.io/t/how-to-observe-objects-in-aurelia-using-the-binding-engine/23

上面的示例运行良好,并且更改了this.myObject的属性observeMe时触发了objectValueChanged 但是,由于某些情况,有时我们希望替换整个对象,但仍然会触发事件。 例:

setInterval(() => {
    this.myObject = { observeMe : 'Test' + new Date()}
    //Object.assign does not work either
    //this.myObject = Object.assign({ observeMe : 'Test' + new Date()}, this.myObject);
}, 2000);

这不会触发objectValueChanged 如果我们需要同时捕获两个属性更改或整个对象都更改了,该怎么办呢?

现在,我们已经解决了它,方法是不创建新对象,而是替换这样的值。 但是,如果我们也可以跟踪对象是否已更改,对我们来说将容易得多。

Object.keys(this.myObject).forEach((key) => {
    this.myObject[key] = newMyObject[key];
});

您可以在BindingEngine上使用expressionObserver来观察包含许多访问器的长路径。 此处的沙盒示例: https//codesandbox.io/s/x3qz6w2k6w

基本上,绑定引擎提供了执行此操作的快捷方式,其内容如下所示:

bindingEngine.createObserverFor(someObject, 'at.this.property.path');

该值将在路径的最终属性的值,它的守卫对null / undefined默认情况下,所以你会得到undefined ,如果任何沿路径属性访问返回null / undefined

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM