属性和集合观察者在Aurelia中没有引发propertyChanged事件



我有一个模型对象表示"球员"在DB。在它的实现有一个数组的球员,我想从不同的VM绑定到我的应用程序。例如:

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();
  }
}

不幸的是,当对玩家数组(从应用程序的其他部分)进行更改时,更改不会反映在_playersCount属性中。例如:绑定到这个属性的UI标签不会被刷新,objectvaluechange也不会被调用。

你在不同的VM中有相同的问题,在同一个数组上有一个collectionObserver

帮忙吗?

您是否尝试在订阅之前在构造函数中声明_playersCount ?

语法似乎也不正确,应该根据这篇文章:

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关键字可能会影响行为。如果它仍然不起作用,您可以使用事件聚合器来广播更改。