我有一个代表数据库中“玩家”的模型对象。在它的实现中,有一系列玩家,我想从我的应用程序中的不同虚拟机绑定(bind)到它们。例如:
import {Players} from './models/players';
import {inject, BindingEngine} from 'aurelia-framework';
@inject(Players,BindingEngine)
export class App {
constructor(playersProvider,bindingEngine) {
this._playersProvider = playersProvider;
this._bindingEngine = bindingEngine;
this._subscription = this._bindingEngine.propertyObserver(this,this._playersCount)
.subscribe(this.objectValueChanged);
}
async activate() {
await this._playersProvider.initialize();
this._playersCount = this._playersProvider.players.length;
}
objectValueChanged(newVal,oldVal) {
console.log("new : " + newVal + ", old val : " + oldVal);
}
deactivate() {
this._subscription.dispose();
}
}
不幸的是,当对玩家数组(从应用程序中的其他部分)进行更改时,该更改不会反射(reflect)在 _playersCount 属性中。例如- 绑定(bind)到此属性的 UI 标签不会刷新,并且 objectValueChanged 永远不会被调用。
您在同一阵列上具有 collectionObserver 的不同虚拟机中遇到相同的问题。
有什么帮助吗?
最佳答案
您是否尝试在订阅之前在构造函数中声明 _playersCount?
而且合成似乎不正确,它应该根据this article :
import {BindingEngine, inject} from 'aurelia-framework';
@inject(BindingEngine)
class MyClass {
constructor(bindingEngine) {
this.bindingEngine = bindingEngine;
this.observeMe = 'myvalue'; // the property is first initialized in the constructor
let subscription = this.bindingEngine
.propertyObserver(this, 'observeMe') // <= you wrote this._bindingEngine.propertyObserver(this,this.observeMe)
.subscribe(this.objectValueChanged);
// Dispose of observer when you are done via: subscription.dispose();
}
objectValueChanged(newValue, oldValue) {
console.log(`observeMe value changed from: ${oldValue} to:${newValue}`);
}
}
async 关键字可能会影响行为。 如果仍然不起作用,您可以使用事件聚合器来广播更改。
关于javascript - Aurelia 中的 Property and Collection 观察者未引发 propertyChanged 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40096262/