从子组件更改"field.property"时不调用 fieldChanged() 方法



这是我的父视图模型和视图。

export class Parent {
@observable field;
fieldChanged() {
console.log('field has been changed');
}
}
<template>
<child-component field.two-way="field" />
</template>

当我这样做时

this.field.property = 'new value';

在子组件中,不调用fieldChanged方法。

请注意,字段是对象的类型。对于基元类型,它工作得很好。 我可以做一些事情来使它适用于对象类型吗?

如果你想观察一个对象的属性,你可以使用bindingEngine

import { BindingEngine, inject } from 'aurelia-framework';
@inject(BindingEngine)
export class Parent {
field = {
property: ''
}
constructor(bindingEngine) {
this.bindingEngine = bindingEngine;
}
attached() {
this.subscription = this.bindingEngine.propertyObserver(this.field, 'property')
.subscribe((newValue, oldValue) => {
// do your logic here
})
}
detached() {
// Dispose subscription to avoid memory leak
this.subscription.dispose();
}
}

您可以使用BindingEngine.expressionObserver方法来观察路径,而不是单个属性

const observer = bindingEngine
.expressionObserver(this /* or any object */, 'field.property')
.subscribe(newValue => console.log('new field.property is:', newValue))

记得在不再需要时稍后致电observer.dispose()

您可能没有在子组件中声明绑定:

import {bindable} from 'aurelia-framework';
export class ChildComponent
{
@bindable field;
/* DO whatever you want*/
}

顺便说一句: 在你的代码中,你应该有this.field = 'new value';而不是field = 'new value';

最新更新