Aurelia绑定,将函数绑定到对象的属性,而不使用propertyObserver

Aurelia绑定,将函数绑定到对象的属性,而不使用propertyObserver,aurelia,Aurelia,因此,通常,当我想要订阅一个变量时,我只需声明该变量并声明一个函数,该函数的变量名后跟函数末尾的单词“Changed”,如下所示: test = ''; testChanged() { // do stuff here } Aurelia提供了一种很好的处理方法。但是,如果我想订阅对象内部的属性而不使用bindingEngine.propertyObserver 例如: model = { a: '', b: '' } 如何使用与上述相同的约定订阅model.a?您需要使用Obje

因此,通常,当我想要订阅一个变量时,我只需声明该变量并声明一个函数,该函数的变量名后跟函数末尾的单词“Changed”,如下所示:

test = '';

testChanged() {
// do stuff here
}
Aurelia提供了一种很好的处理方法。但是,如果我想订阅对象内部的属性而不使用
bindingEngine.propertyObserver

例如:

model = {
  a: '',
  b: ''
}

如何使用与上述相同的约定订阅
model.a

您需要使用Object.defineProperty方法查看对象特定属性的更改。我相信这就是Aurelia
@bindable
@observable
方法在大多数情况下在幕后的工作方式

Object.defineProperty(this.model, 'a', {
    configurable: true,
    enumerable: true,
    get: () => {
        return this.model.__a;
    },
    set: (v) => {
        this.model.__a = v;
        this.modelChanged(v);
    }
});
首先值得一提的是,在setter方法
set
中,您不能设置原始值,否则它将触发递归循环并抛出堆栈错误,因此您将该值分配给一个双下划线前缀名称,类似于临时隐藏变量

然后在类中定义回调函数:

modelChanged(value) {
    console.log(value);
}
export class MyViewModel {
    model = {
        a: '',
        b: ''
    };    

    constructor() {
        Object.defineProperty(this.model, 'a', {
            configurable: true,
            enumerable: true,
            get: () => {
                return this.model.__a;
            },
            set: (v) => {
                this.model.__a = v;
                this.modelChanged(v);
            }
        });

        setTimeout(() => {
            this.model.a = 'HELLO!';
        }, 3000);
    }

    modelChanged(value) {
        console.log(value); // After 3 seconds, this should be "HELLO!" in the browser console.
    }
}
最后,将其全部绑定在一起,并使用setTimeout进行测试:

modelChanged(value) {
    console.log(value);
}
export class MyViewModel {
    model = {
        a: '',
        b: ''
    };    

    constructor() {
        Object.defineProperty(this.model, 'a', {
            configurable: true,
            enumerable: true,
            get: () => {
                return this.model.__a;
            },
            set: (v) => {
                this.model.__a = v;
                this.modelChanged(v);
            }
        });

        setTimeout(() => {
            this.model.a = 'HELLO!';
        }, 3000);
    }

    modelChanged(value) {
        console.log(value); // After 3 seconds, this should be "HELLO!" in the browser console.
    }
}
说到这里,值得一提的是bindingEngine.propertyObserver的功能本质上也是一样的。我会诚实地考虑只使用<代码> PrimyTeals,而不是在你的应用程序中引入一堆代码来监视属性。