从子组件更改 "field.property" 时未调用 fieldChanged() 方法
fieldChanged() method not called when "field.property" is changed from child component
这是我的父视图模型和视图。
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 方法未被调用。
请注意,该字段是 对象 的类型。对于原始类型,它运行良好。
我可以做些什么来使这项工作适用于对象类型吗?
您可能没有在子组件中声明绑定:
import {bindable} from 'aurelia-framework';
export class ChildComponent
{
@bindable field;
/* DO whatever you want*/
}
顺便说一句:
在你的代码中你应该有 this.field = 'new value';
而不是 field = 'new value';
如果你想观察一个属性的物体,你可以使用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()
。
这是我的父视图模型和视图。
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 方法未被调用。
请注意,该字段是 对象 的类型。对于原始类型,它运行良好。 我可以做些什么来使这项工作适用于对象类型吗?
您可能没有在子组件中声明绑定:
import {bindable} from 'aurelia-framework';
export class ChildComponent
{
@bindable field;
/* DO whatever you want*/
}
顺便说一句:
在你的代码中你应该有 this.field = 'new value';
而不是 field = 'new value';
如果你想观察一个属性的物体,你可以使用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()
。