javascript - Aurelia 中的 Property and Collection 观察者未引发 propertyChanged 事件

标签 javascript aurelia

我有一个代表数据库中“玩家”的模型对象。在它的实现中,有一系列玩家,我想从我的应用程序中的不同虚拟机绑定(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/

相关文章:

aurelia - Aurelia 中的动态路由 - 更改标题

javascript - Aurelia Babel 未知选项 base.modules 错误

javascript - 在 Node.js 中写入文件时创建目录

javascript - React - 调用父组件中的函数来访问状态

javascript - 使用 Aurelia 动态渲染 html

javascript - 如何使用路由器和内置/自定义属性在 aurelia 中创建下拉菜单?

aurelia - Aurelia 模板绑定(bind)错误

javascript - 使用 Mongoose 模型设置 typescript

javascript - 为什么我的跨度没有显示在 IE9 中?

javascript - 比较文章和按钮的数据